赞
踩
https://leetcode-cn.com/problems/top-k-frequent-elements/
示例1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例2:
输入: nums = [1], k = 1
输出: [1]
提示:
1 <= nums.length <= 105
k 的取值范围是 [1, 数组中不相同的元素的个数]
题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的
思路:
- 任意顺序很容易想到hash来处理
- 设想1:hashmap存储值以及个数,最后取出对应k大,过于复杂
- 优化:参考快排思路,对筛选数据进行处理
package sj.shimmer.algorithm.m4_2021; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import sj.shimmer.algorithm.Utils; /** * Created by SJ on 2021/4/30. */ class D93 { public static void main(String[] args) { Utils.logArray(topKFrequent(new int[]{1,1,1,2,2,3},2)); } public static int[] topKFrequent(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<>(); for (int num : nums) { Integer size = map.getOrDefault(num, 0); size++; map.put(num, size); } List<int[]> values = new ArrayList<>(); for (Map.Entry<Integer, Integer> entry : map.entrySet()) { int key = entry.getKey(); int count = entry.getValue(); values.add(new int[]{key, count}); } int[] result = new int[k]; qsort(values, 0, values.size() - 1, result, 0, k); return result; } public static void qsort(List<int[]> values, int start, int end, int[] ret, int retIndex, int k) { int picked = (int) (Math.random() * (end - start + 1)) + start; Collections.swap(values, picked, start); int pivot = values.get(start)[1]; int index = start; for (int i = start + 1; i <= end; i++) { if (values.get(i)[1] >= pivot) { Collections.swap(values, index + 1, i); index++; } } Collections.swap(values, start, index); if (k <= index - start) { qsort(values, start, index - 1, ret, retIndex, k); } else { for (int i = start; i <= index; i++) { ret[retIndex++] = values.get(i)[0]; } if (k > index - start + 1) { qsort(values, index + 1, end, ret, retIndex, k - (index - start + 1)); } } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。