题目:
给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。
示例 1:
输入: [3,2,3]
输出: 3
示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2
用map记录每一个数字出现的个数
class Solution {
public int majorityElement(int[] nums) {
int result=0;
float t=nums.length/2;
Map<Integer,Integer>map=new HashMap<Integer,Integer>();
for (int i=0;i<nums.length;i++){
if(map.get(nums[i])!=null){
map.put(nums[i],map.get(nums[i])+1);
}
else{
map.put(nums[i],1);
}
if(map.get(nums[i])>t){
result=nums[i];
}
}
return result;
}
}
摩尔投票法:
从第一个数开始count=1,遇到相同的就加1,遇到不同的就减1,减到0就重新换个数开始计数,总能找到最多的那个。
众数遇到“最坏”的情况也能在遍历完之后count等于1;
public int majorityElement(int[] nums) {
int count = 1;
int maj = nums[0];
for (int i = 1; i < nums.length; i++) {
if (maj == nums[i])
count++;
else {
count--;
if (count == 0) {
maj = nums[i + 1];
}
}
}
return maj;
}
方法三:处于中间位置的总是众数
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
}