C++的按照Map 来进行排序
给你一个整数数组 nums
,请你将数组按照每个值的频率 升序 排序。如果有多个值的频率相同,请你按照数值本身将它们 降序 排序。
请你返回排序后的数组。
示例 1:
输入:nums = [1,1,2,2,2,3] 输出:[3,1,1,2,2,2] 解释:'3' 频率为 1,'1' 频率为 2,'2' 频率为 3 。
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> frequencySort(vector<int>& nums) {
unordered_map<int, int> hash;//hash计数
for (int i = 0; i < nums.size(); i++) {
hash[nums[i]]++;
}
vector<int> res;
vector<pair<int, int>> arr;
for(auto it : hash) {
arr.emplace_back(it);
}
// 重写compare函数,如果value值相同,则按照key值排序
sort(arr.begin(), arr.end(), [](auto p1, auto p2){
return p1.second == p2.second ? p1.first > p2.first
: p1.second < p2.second;
});
for(auto it:arr) {
cout<<it.first<<" "<<it.second<<endl;
}
cout<<endl;
for(auto it: arr) {
for(int i=0;i<it.second;i++) {
res.push_back(it.first);
}
}
return res;
}
};
int main() {
vector<int> nums {1,1,2,2,2,3};
Solution s2;
vector<int> res;
res = s2.frequencySort(nums);
for(auto i:res) {
cout<<i<<" ";
}
return 0;
}
Java 的实现方式
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
public class Main {
public int[] frequencySort(int[] nums) {
HashMap<Integer, Integer> val2cnt = new HashMap<>();
for (int x : nums) {
val2cnt.merge(x, 1, Integer::sum);
}
return Arrays.stream(nums)
.boxed()
.sorted(Comparator.<Integer>comparingInt(val2cnt::get)
.thenComparing(Comparator.reverseOrder()))
.mapToInt(Integer::intValue)
.toArray();
}
public static void main(String[] args) {
int[] nums = {3,2,2,2,1,1,};
int[] res;
res = new Main().frequencySort(nums);
for(var i:res) {
System.out.print(i+" ");
}
}
}
常规的实现,没有用到 Java 流等相关转换
public class Main {
public int[] frequencySort(int[] nums) {
Map<Integer,Integer> map = new HashMap<>();
for(int num:nums){
map.put(num,map.getOrDefault(num,0)+1);
}
List<Map.Entry<Integer,Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list,(o1, o2)->{
if(o1.getValue()==o2.getValue()) {
return o2.getKey() - o1.getKey();
}
return o1.getValue()-o2.getValue();
});
int[] res = new int[nums.length];
int index = 0;
for(Map.Entry<Integer,Integer> m:list){
for(int i = 0; i < m.getValue();++i){
res[index++] = m.getKey();
}
}
return res;
}
public static void main(String[] args) {
int[] nums = {3,2,2,2,1,1,};
int[] res;
res = new Main().frequencySort(nums);
for(var i:res) {
System.out.print(i+" ");
}
}
}