题目描述:
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
HashMap 的方法很简答,不描述了,待会儿直接上代码。
摩尔投票法能保证空间使用为O(1)!
摩尔投票法的解法:
由与一个数组中次数大于1/2的数字只可能有一个,所以就用一个m保存majority element的candidate,用cm保存其出现次数,遍历数组的时候,如果遇到与此candidate不同的数,就在cm中抵消一次,如果相同,就在cm中加上一。这样就相当于把数组中两两不同的数一对一对地消除,最后剩下的就可能是真正的candidate。然后再遍历一遍数组,统计此candidate的次数,如果次数大于threshhold,就返回,否则,则不存在。(此解法的代码参见Majority ElementII)
HashMap 法
public class Solution {
public int majorityElement(int[] nums) {
HashMap <Integer,Integer>h=new HashMap<Integer,Integer>();
int times=0;
int threshhold=(int)(Math.ceil(nums.length/2));
for(int n:nums){
if(h.containsKey(n)){
times=h.get(n);
times++;
h.put(n,times);
}
else
h.put(n,1);
}
for(int n:nums){
if(h.get(n)>threshhold)
return n;
}
return 0;
}
}