문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음
정수 배열 nums가 주어졌을 때, 값의 빈도를 기준으로 배열을 오름차순으로 정렬해라. 같은 빈도를 가진 여러 개의 값이 있다면, 내림차순으로 정렬해라.
정렬된 배열을 반환해라.
#1
Input: nums = [1, 1, 2, 2, 2, 3]
Output: [3, 1, 1, 2, 2, 2]
Explanation: 3은 빈도 1, 1은 빈도 2, 2는 빈도 3을 가진다.
#2
Input: nums = [2, 3, 1, 3, 2]
Output: [1, 3, 3, 2, 2]
Explanation: 2와 3 둘 다 빈도 2를 가져서, 내림차순으로 정렬한다.
#3
Input: nums = [-1, 1, -6, 4, 5, -6, 1, 4, 1]
Output: [5, -1, 4, 4, -6, -6, 1, 1, 1]
class Solution {
public int[] frequencySort(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>();
for(int num : nums){
map.put(num, map.getOrDefault(num, 0) + 1);
}
Integer[] arr = new Integer[nums.length];
for(int i = 0; i < nums.length; i++){
arr[i] = nums[i];
}
Arrays.sort(arr, (a, b) -> {
if(map.get(a).equals(map.get(b))){
return Integer.compare(b, a);
}
return Integer.compare(map.get(a), map.get(b));
});
for(int i = 0; i < nums.length; i++){
nums[i] = arr[i];
}
return nums;
}
}