马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
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[i], map.getOrDefault(nums[i],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[obj.length- 1-i].toString())))
{
i++;
list.add(key);
map.remove(key);
break;
}
}
}
return list;
}
}
|