题目
标题和出处
标题:按照频率将数组升序排序
难度
3 级
题目描述
要求
给定一个整数数组 nums \texttt{nums} nums,将数组按照每个值的频率升序排序。如果有多个值的频率相同,按照数值本身将它们降序排序。
返回排序后的数组。
示例
示例 1:
输入:
nums
=
[1,1,2,2,2,3]
\texttt{nums = [1,1,2,2,2,3]}
nums = [1,1,2,2,2,3]
输出:
[3,1,1,2,2,2]
\texttt{[3,1,1,2,2,2]}
[3,1,1,2,2,2]
解释:
3
\texttt{3}
3 的频率为
1
\texttt{1}
1,
1
\texttt{1}
1 的频率为
2
\texttt{2}
2,
2
\texttt{2}
2 的频率为
3
\texttt{3}
3。
示例 2:
输入:
nums
=
[2,3,1,3,2]
\texttt{nums = [2,3,1,3,2]}
nums = [2,3,1,3,2]
输出:
[1,3,3,2,2]
\texttt{[1,3,3,2,2]}
[1,3,3,2,2]
解释:
2
\texttt{2}
2 和
3
\texttt{3}
3 的频率都为
2
\texttt{2}
2,所以它们之间按照数值本身降序排序。
示例 3:
输入:
nums
=
[-1,1,-6,4,5,-6,1,4,1]
\texttt{nums = [-1,1,-6,4,5,-6,1,4,1]}
nums = [-1,1,-6,4,5,-6,1,4,1]
输出:
[5,-1,4,4,-6,-6,1,1,1]
\texttt{[5,-1,4,4,-6,-6,1,1,1]}
[5,-1,4,4,-6,-6,1,1,1]
数据范围
- 1 ≤ nums.length ≤ 100 \texttt{1} \le \texttt{nums.length} \le \texttt{100} 1≤nums.length≤100
- -100 ≤ nums[i] ≤ 100 \texttt{-100} \le \texttt{nums[i]} \le \texttt{100} -100≤nums[i]≤100
解法
思路和算法
这道题要求将给定的数组按照元素频率排序,因此需要获得每个元素的频率,然后排序。
首先遍历数组获得每个元素的频率,然后定义二元组类型存储每个元素的元素值和频率,使用列表存储全部二元组,并对列表排序。列表排序的依据如下:
-
如果两个二元组的频率不同,则根据频率升序排序;
-
如果两个二元组的频率相同,则根据元素值降序排序。
遍历排序后的列表,对于列表中的每个二元组,将元素值根据频率填入排序后的数组中。遍历结束之后即可得到完整的排序后的数组。
代码
class Solution {
class Pair {
int num;
int freq;
public Pair(int num, int freq) {
this.num = num;
this.freq = freq;
}
}
public int[] frequencySort(int[] nums) {
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
for (int num : nums) {
counts.put(num, counts.getOrDefault(num, 0) + 1);
}
List<Pair> pairs = new ArrayList<Pair>();
Set<Map.Entry<Integer, Integer>> entries = counts.entrySet();
for (Map.Entry<Integer, Integer> entry : entries) {
int num = entry.getKey();
int freq = entry.getValue();
pairs.add(new Pair(num, freq));
}
Collections.sort(pairs, (a, b) -> {
if (a.freq != b.freq) {
return a.freq - b.freq;
} else {
return b.num - a.num;
}
});
int length = nums.length;
int[] sorted = new int[length];
int index = 0;
for (Pair pair : pairs) {
int num = pair.num;
int freq = pair.freq;
for (int i = 0; i < freq; i++) {
sorted[index++] = num;
}
}
return sorted;
}
}
复杂度分析
-
时间复杂度: O ( n log n ) O(n \log n) O(nlogn),其中 n n n 是数组 nums \textit{nums} nums 的长度。排序需要 O ( n log n ) O(n \log n) O(nlogn) 的时间,每次遍历都需要 O ( n ) O(n) O(n) 的时间,因此时间复杂度是 O ( n log n ) O(n \log n) O(nlogn)。
-
空间复杂度: O ( n ) O(n) O(n),其中 n n n 是数组 nums \textit{nums} nums 的长度。哈希表和列表都需要 O ( n ) O(n) O(n) 的空间。