169. Majority Element - LeetCode
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了169. Majority Element - LeetCode相关的知识,希望对你有一定的参考价值。
Question
Solution
思路:构造一个map存储每个数字出现的次数,然后遍历map返回出现次数大于数组一半的数字.
还有一种思路是:对这个数组排序,次数超过n/2的元素必然在中间.
Java实现:
public int majorityElement(int[] nums) {
Map<Integer, Integer> countMap = new HashMap<>();
for (int num : nums) {
Integer count = countMap.get(num);
if (count == null) {
count = 0;
}
countMap.put(num, count+1);
}
for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
if (entry.getValue() > nums.length/2) {
return entry.getKey();
}
}
return 0;
}
在讨论区看到一个创新的解法:
public int majorityElement(int[] num) {
int major=num[0], count = 1;
for(int i=1; i<num.length;i++){
if(count==0){
count++;
major=num[i];
}else if(major==num[i]){
count++;
}else count--;
}
return major;
}
这是讨论中对该解法的一个说明:
1)According to problem Major element appears more than ? n/2 ? times
2)Count is taken as 1 because 1 is the least possible count for any number ,
3)Major element is updated only when count is 0 which means --Array has got as many non major elements as major element
4) Check this case 1,1,3,3,5,3,3 ---Majority element is 1 initially count becomes 0 at after 2nd 3 and 5 is made as majority element with count=1 and finally 3 is made as major element.
Major Element是出现次数大于n/2的一个数,遍历这个数组时,只有Major Element才能保证count>0.
以上是关于169. Majority Element - LeetCode的主要内容,如果未能解决你的问题,请参考以下文章