题目:
思路:
这个题其实和在数组中找出只出现过一次的数这种题有点类似,用HashMap来求解,那基本上就是完全一样,就条件判断那里不一样。用HashMap键值对来存储,键存储的是数组中的元素,键对应的值存储的元素出现的次数,然后对map进行遍历,判断出现的次数是不是> n/3,,将符合条件的结果存入list中
答案:
class Solution {
public List<Integer> majorityElement(int[] nums) {
Map<Integer,Integer> map = new HashMap<>();
for(Integer num : nums){
Integer count = map.get(num);
count = (count==null)?1:++count;
map.put(num,count);
}
List<Integer> list = new ArrayList<>();
for(Integer key : map.keySet()){
if(map.get(key) > (nums.length/3)){
list.add(key);
}
}
return list;
}
}