Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Solution {
public int[] frequencySort(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
List<Integer> list = new ArrayList<>();
//统计次数
for (int num : nums) {
list.add(num);
map.put(num, map.getOrDefault(num, 0) + 1);
}
//按规则排序
list.sort((a, b) -> {
int num1 = map.get(a);
int num2 = map.get(b);
if (num1 == num2) {
return b - a;
}
return num2 - num1;
});
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
res[i] = list.get(i);
}
return res;
}
}
c++ 可以用 std::sort() 函数
先来个示例
#include <iostream>
#include <algorithm>
int main() {
int frequencies[] = {5, 3, 8, 1, 2, 9, 4, 7, 6};
int n = sizeof(frequencies) / sizeof(frequencies[0]);
std::sort(frequencies, frequencies + n,
[](int a, int b) {return a > b;});
for (int i = 0; i < n; i++) {
std::cout << frequencies[i] << " ";
}
return 0;
}
上述java代码的c++实现
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
std::vector<int> frequencySort(std::vector<int> nums) {
std::unordered_map<int, int> map;
std::vector<int> list;
// 统计次数
for (int num : nums) {
list.push_back(num);
if (map.find(num) == map.end()) {
map[num] = 1;
} else {
map[num]++;
}
}
// 按规则排序
std::sort(list.begin(), list.end(), [&](int a, int b) {
int num1 = map[a];
int num2 = map[b];
if (num1 == num2) {
return b > a;
}
return num1 > num2;
});
std::vector<int> res(list.size());
for (size_t i = 0; i < list.size(); i++) {
res[i] = list[i];
}
return res;
}
int main() {
std::vector<int> nums = {6, 1, 6, 4, 4, 4, 4, 5, 2};
std::vector<int> sortedNums = frequencySort(nums);
for (int num : sortedNums) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}