题目链接 点击打开链接
答案
public class Solution {
public int majorityElement(int[] nums) {
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++)
{
Integer valueT=map.get(nums[i]);
if(valueT==null)
{
map.put(nums[i], 1);
}
else
{
map.put(nums[i], valueT+1);
}
}
final int threshold=nums.length/2;
Set<Map.Entry<Integer,Integer>> entrySet=map.entrySet();
for(Map.Entry<Integer,Integer> e:entrySet)
{
if(e.getValue()>threshold)
{
return e.getKey();
}
}
//这里并不能达到但是java必须要有返回值
return 0;
}
}
本文介绍了一种利用哈希表解决寻找数组中出现次数超过一半元素的方法,通过遍历数组并更新哈希表中的计数值,最终找到满足条件的元素。
1327

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



