Given an array of size n, find the majority element. The majority element is the element that appearsmore than [ n/2 ]
times.
You may assume that the array is non-empty and the majority element always exist in the array.
题意:给定一个大小为n的数组,查找多数元素。大多数元素是出现频率超过[N / 2]次的元素。假设数组是非空的,并且多数元素总是存在于数组中。
看见题目直接暴力解决,将数组的字面值作为map的key,出现次数作为value全部统计一次,出现次数一旦大于n/2就返回这个key。
public int majorityElement(int[] nums) {
Arrays.sort(nums);
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(nums[0], 1);
int count = 0;
for (int i = 1; i < nums.length; i++) {
if(nums[i]==nums[i-1]){
count = map.get(nums[i-1])+1;
if(count>nums.length/2){return nums[i];}
map.remove(nums[i-1]);
map.put(nums[i], count);
}else{
map.put(nums[i], 1);
}
}
return -1;
}
然后再回头看看题目,这个元素一定存在,而且数组不为空,也就是说当数组长度为偶数时不可能出现类似[1,1,2,2]的数组,而且这个元素的出现的次数是大于n/2次的。于是经过排序后就会出现一个神奇的事情,下标为n/2的那个元素就是那个出现次数最多的那个元素。
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2]
}
也许你会出现这样的疑问当n=3时,nums[1.5]会出现什么情况,别担心他会给你返回nums[(int)1.5]=nums[1]的值正好是那个中间值。问题得到高效简洁的解决。