您的位置:首页 > 编程语言 > Java开发

[Leetcode] 229. 求众数 II java hashmap

2018-10-27 21:09 246 查看

 给定一个大小为 n 的数组,找出其中所有出现超过 

⌊ n/3 ⌋
 次的元素。

说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1)。

示例 1:

输入: [3,2,3]
输出: [3]

示例 2:

输入: [1,1,1,3,3,2,2,2]
输出: [1,2]
[code]class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> list=new ArrayList<>();
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
int l=nums.length;
if(l==0) return list;
if(l==1) {
list.add(nums[0]);
return list;
}
for(int i=0;i<l;i++){
if(map.containsKey(nums[i])){
if(map.get(nums[i])==l/3) list.add(nums[i]);
map.put(nums[i],map.get(nums[i])+1);
}
else{
map.put(nums[i],1);
if(1>l/3){//list长度为2时
list.add(nums[i]);
}
}
}
return list;
}
}

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: