public class Solution {
public int majorityElement(int[] nums) {
//解法一:利用Map来统计数组中的元素的出现次数
int res = 0;
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
if(map.containsKey(nums[i])){
map.put(nums[i], map.get(nums[i]) + 1);
}
else{
map.put(nums[i], 1);
}
}
for(int key : map.keySet()){
if(map.get(key) > (nums.length / 2)){
res = key;
return res;
}
}
return res;
}
}
leetcode [Majority Element]//待整理多种解法
最新推荐文章于 2023-08-07 22:33:15 发布