You may assume that the array is non-empty and the majority element always exist in the array.
Idea: Scan the array from left to right. Use a Hashmap<value, times appeared> to record how many times each value shows up. Once a value shows up more than floor(n/2) times, return it as the result.
Time: O(n) Space: O(n)
Code:
public class Solution {
public int majorityElement(int[] num) {
HashMap<Integer,Integer> appeared=new HashMap<Integer,Integer>();
int threshold=num.length/2;
for(int i:num)
{
if(appeared.containsKey(i))
appeared.put(i,appeared.get(i)+1);
else
appeared.put(i,1);
if(appeared.get(i)>threshold)
return i;
}
return -1;
}
}
This should be possible in O(n) time and O(1) space. See the algorithm introduction here:
ReplyDeletehttp://www.sysexpand.com/?path=exercises/majority-element