哈希排序算法,
package hot;import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;public class Solution347 {public static void main(String[] args) {int[] nums = {1,1,1,2,2,3};Solution347 solution = new Solution347();System.out.println(Arrays.toString(solution.method(nums, 2)));}private int[] method(int[] nums, int k){int[] res = new int[k];Map<Integer, Integer> map = new HashMap<>();Queue<Map.Entry<Integer, Integer>> heap = new PriorityQueue<>(new Comparator<Map.Entry<Integer, Integer>>() {@Overridepublic int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {return o2.getValue() - o1.getValue();}});for(int n : nums){if(map.containsKey(n)){map.put(n, map.get(n) + 1);}else{map.put(n, 1);}}for(Map.Entry<Integer, Integer> entry : map.entrySet()){heap.offer(entry);}for(int i = 0; i < k; i++){res[i] = heap.poll().getKey();}return res;}
}//时间复杂度为 O(mlogn)
//空间复杂度为 O(n)
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态