给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2 输出: [1,2]
示例 2:
输入: nums = [1], k = 1 输出: [1]
提示:
- 你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
- 你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。
- 题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的。
- 你可以按任意顺序返回答案。
package Solution347;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
class Solution {
public int[] topKFrequent(int[] nums, int k) {
ArrayList<Integer> al = new ArrayList<Integer>();
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (hm.containsKey(nums[i])) {
hm.put(nums[i], hm.get(nums[i]) + 1);
} else {
hm.put(nums[i], 1);
}
}
int count = 0;
Map<Integer, Integer> hm1 = sortByValue(hm);
for (Map.Entry<Integer, Integer> en : hm1.entrySet()) {
if (count < k) {
// System.out.println(en.getKey());
al.add(en.getKey());
count++;
}
}
int[] out = new int[al.size()];
for (int i = 0; i < al.size(); i++) {
out[i] = al.get(i);
}
return out;
}
// function to sort hashmap by values
public static HashMap<Integer, Integer> sortByValue(HashMap<Integer, Integer> hm) {
// Create a list from elements of HashMap
List<Map.Entry<Integer, Integer>> list = new LinkedList<Map.Entry<Integer, Integer>>(hm.entrySet());
// Sort the list
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
return (o2.getValue()).compareTo(o1.getValue());
}
});
// put data from sorted list to hashmap
HashMap<Integer, Integer> temp = new LinkedHashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> aa : list) {
temp.put(aa.getKey(), aa.getValue());
}
return temp;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = { 1, 1, 1, 2, 2, 3 };
int k = 2;
System.out.println(Arrays.toString(sol.topKFrequent(nums, k)));
}
}