/*
Given an integer array of size n, find all elements that appear
more than ⌊ n/3 ⌋ times.
The algorithm should run in linear time and in O(1) space.
*/
public class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> list = new ArrayList<Integer>();
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
int len = nums.length;
int m = len/3;
for(int num:nums) {
if(!map.containsKey(num)) {
map.put(num,1);
} else {
int count = map.get(num);
count++;
map.put(num,count);
}
}
for(Map.Entry<Integer,Integer> entry:map.entrySet()) {
if(entry.getValue() > m) {
list.add(entry.getKey());
}
}
return list;
}
}
leetcode-java-229. Majority Element II
最新推荐文章于 2022-04-25 07:45:00 发布
本文介绍了一个线性时间和O(1)空间复杂度的算法,用于找出数组中出现次数超过n/3的所有元素。该算法使用HashMap来记录每个元素的出现次数,并返回符合条件的元素列表。
534

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



