给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。
示例 1:
输入: [3,2,3]
输出: 3
示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2
以上是题目
方法一:利用哈希表,key用来存数组的元素,value用来存元素出现的次数。插入时判断表中是否出现,如果出现将出现次数加1,如果没有出现,将他插入表中,并设置出现次数为1。遍历表查询比数组/2 的数 返回即可。
public int majorityElementHash(int[] nums){
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for (int i = 0; i < nums.length; i++) {
if(!map.containsKey(nums[i])){
map.put(nums[i], 1);
}else{
map.put(nums[i], map.get(nums[i])+1);
}
}
int condition = nums.length/2;
int res =0;
for (Integer key : map.keySet()) {
if(map.get(key)>condition){
res = key;
break;
}
}
return res;
}
方法二:摩尔投票法 Moore Voting。 我们将数组的第一个数假设为众数,与下一个数比较是否相等,若相等则将计数器加一,,反之减一。若计数器为0时,则将下一个数假设为众数,以此类推知道遍历整个数组,最后的数即为众数
public int majorityElement(int[] nums){
int result = nums[0];
int count = 1;
for (int i = 1; i < nums.length; i++) {
if (result==nums[i]) {
count++;
} else {
count--;
if(count==0){
result=nums[++i];
count++;
}
}
}
return result;
}