您的位置:首页 > 其它

leetcode-Majority Element

2015-11-04 22:05 218 查看
用哈希表保存出现的次数即可。

public class Solution {
public int majorityElement(int[] nums) {
int max=0,result=0,curLen=0;
HashMap<Integer,Integer> ha=new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++)
{

if(!ha.containsKey(nums[i]))
ha.put(nums[i], 1);
else
{
curLen=ha.get(nums[i]);
curLen++;
ha.put(nums[i], curLen);
}
curLen=ha.get(nums[i]);
if(curLen>max)
{
max=curLen;
result=nums[i];
}
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: