力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
class Solution {
public int majorityElement(int[] nums) {
int res = 0;
Map<Integer, Integer> counts = countNums(nums);
Set<Map.Entry<Integer, Integer>> lists = counts.entrySet();
for (Map.Entry<Integer, Integer> entry : lists) {
if(entry.getValue() > nums.length/2){
res = entry.getKey();
break;
}
}
return res;
}
// 先得到一个HashMap 键代表元素的值 --> 值代表元素出现的次数
private Map<Integer, Integer> countNums(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;
}
}
或者
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
}
}