Q169 Majority Element
Since majority element ALWAYS exists,utilize Moore voting algorithm.
O(n)
O(1)
public class Solution {
public int majorityElement(int[] nums) {
int temp = nums[0];
int count = 0;
for(int n : nums) {
if(n == temp) {
count++;
}
else {
count--;
}
if(count == 0) {
temp = n;
count = 1;
}
}
return temp;
}
}
HashMap is an effective to avoid duplicated elements in collection.
O(n)
O(n)
public class Solution {
public int majorityElement(int[] nums) {
Map<Integer,Integer> hash = new HashMap<Integer,Integer>();
for (int key: nums)
if (!hash.containsKey(key))
hash.put(key,0);
else
hash.put(key,hash.get(key)+1);
for (Map.Entry<Integer,Integer> entry: hash.entrySet())
if (entry.getValue() >= nums.length/2)
return entry.getKey();
return 0;
}
}