题目
给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。
示例 1:
输入: [3,2,3]
输出: 3
示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2
思路
输入一个数组,众数是在数组中出现大于[n/2]的元素
使用map 来存数组 < 编号,num >
class Solution {
public int majorityElement(int[] nums) {
Map<Integer,Integer> map = new HashMap<>();
Integer size = 0;
for(int i = 0; i < nums.length; i++){
size = map.get(nums[i]);
if(size==null){
map.put(nums[i],1);
}else{
map.put(nums[i],size+1);
}
}
int num = -1;
int maxValue = 0;
Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, Integer> entry = it.next();
if(entry.getValue()> maxValue){
maxValue = entry.getValue();
num = entry.getKey();
}
}
return num;
}
}
本文介绍了一种通过哈希映射实现的寻找众数算法。该算法适用于数组中存在众数的情况,即某个元素出现的次数超过数组长度的一半。通过遍历数组并使用哈希表记录每个元素出现的频率,最终找出出现次数最多的元素作为众数。
1055

被折叠的 条评论
为什么被折叠?



