169. 多数元素
目录
题目链接
题目
解题思路
代码
题目链接
169. 多数元素 - 力扣(LeetCode)
题目
解题思路
法一:哈希表统计个数
法二:摩尔投票法,相同+1,不同-1,最后剩下的肯定是大于n/2的元素的值
代码
法一:
class Solution {private Map<Integer,Integer> ountNums(int[] nums){Map<Integer,Integer> counts=new HashMap<Integer,Integer>();for(int num:nums){if(!counts.containsKey(num)){counts.put(num,1);}else{counts.put(num,counts.get(num)+1);}}return counts;}public int majorityElement(int[] nums) {Map<Integer,Integer> counts=ountNums(nums);Map.Entry<Integer,Integer> majority=null;for(Map.Entry<Integer,Integer> entry:counts.entrySet()){if(majority==null||entry.getValue()>majority.getValue()){majority=entry;}}return majority.getKey();}
}
法二:
class Solution {public int majorityElement(int[] nums) {int x=0,val=0;for(int num:nums){if(val==0) x=num;val+=x==num?1:-1;}return x;}
}