[LeetCode] 1636. Sort Array by Increasing Frequency
Given an array of integers nums
, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order.
Return the sorted array.
Example 1:
Input: nums = [1,1,2,2,2,3] Output: [3,1,1,2,2,2] Explanation: '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3.
Example 2:
Input: nums = [2,3,1,3,2] Output: [1,3,3,2,2] Explanation: '2' and '3' both have a frequency of 2, so they are sorted in decreasing order.
Example 3:
Input: nums = [-1,1,-6,4,5,-6,1,4,1] Output: [5,-1,4,4,-6,-6,1,1,1]
Constraints:
1 <= nums.length <= 100
-100 <= nums[i] <= 100
按照频率将数组升序排序。
给你一个整数数组 nums
,请你将数组按照每个值的频率 升序 排序。如果有多个值的频率相同,请你按照数值本身将它们 降序 排序。 请你返回排序后的数组。
思路就是排序,先用 hashmap 统计每个数字的出现次数,然后对于出现次数相同的数字,我们再按降序排列。这里我先用一个类似451题的 bucket sort 将出现次数相同的数字归在一起。然后当我再次遍历 bucket 的时候,这里需要自己实现一个 comparator 将同一个 bucket 中的元素按降序排列。
时间O(nlogn) - worst case
空间O(n) - bucket
Java实现
1 class Solution { 2 public int[] frequencySort(int[] nums) { 3 HashMap<Integer, Integer> map = new HashMap<>(); 4 for (int num : nums) { 5 map.put(num, map.getOrDefault(num, 0) + 1); 6 } 7 8 List<Integer>[] bucket = new List[101]; 9 for (int key : map.keySet()) { 10 int freq = map.get(key); 11 if (bucket[freq] == null) { 12 bucket[freq] = new ArrayList<>(); 13 } 14 bucket[freq].add(key); 15 } 16 17 int[] res = new int[nums.length]; 18 int index = 0; 19 for (int i = 0; i < bucket.length; i++) { 20 if (bucket[i] != null) { 21 List<Integer> keyList = bucket[i]; 22 Collections.sort(keyList, Collections.reverseOrder()); 23 for (int j = 0; j < keyList.size(); j++) { 24 int k = keyList.get(j); 25 int count = map.get(k); 26 while (count != 0) { 27 res[index++] = k; 28 count--; 29 } 30 } 31 } 32 } 33 return res; 34 } 35 }
相关题目
451. Sort Characters By Frequency