leetcode 347. Top K Frequent Elements
Given a non-empty array of integers, return the k most frequent elements.Example 1:
Input: nums = , k = 2
Output:
Example 2:
Input: nums = , k = 1
Output:
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
import java.util.Collection;
class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
List<Integer> list = new ArrayList<>();
HashMap <Integer,Integer> map = new HashMap<>();
for(int i = 0; i< nums.length; i++){
map.put(nums, map.getOrDefault(nums,0)+1);
}
Collection<Integer> c = map.values();
Object[] obj = c.toArray();
Arrays.sort(obj);
int i = 0;
while(k-- != 0){
for(Integer key : map.keySet()){
if (map.get(key).equals(Integer.parseInt(obj.toString())))
{
i++;
list.add(key);
map.remove(key);
break;
}
}
}
return list;
}
}
页:
[1]