Coding
229. Majority Element II
On this page
⭐⭐⭐
題目敘述
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
Example 1
Input: nums = [3,2,3] Output: [3]
Example 2
Input: nums = [1] Output: [1]
Example 3
Input: nums = [1,2] Output: [1,2]
解題思路
Solution
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> ans = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<>();
int up = nums.length / 3;
for(int num : nums){
map.put(num, map.getOrDefault(num, 0) + 1);
}
for(int key : map.keySet()){
if(map.get(key) > up){
ans.add(key);
}
}
return ans;
}
}