这道题最重要的是善用Collections比较器!
/**
* Runtime: 6 ms, faster than 63.89%
* Memory Usage: 39.4 MB, less than 42.07%
*/
class Solution {
public int[] frequencySort(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int num : nums) { // count times of each element
map.put(num, map.getOrDefault(num, 0) + 1);
}
ArrayList<Integer> numList = new ArrayList(map.keySet());
Collections.sort(numList, (a, b) -> {
int cntA = map.get(a), cntB = map.get(b);
return cntA == cntB ? b - a : cntA - cntB;
});
int i = 0;
for (int num : numList) {
for (int j = 0; j < map.get(num); j++) {
nums[i++] = num;
}
}
return nums;
}
}