1636. Sort Array by Increasing Frequency
Given an array of integers nums
, sort the array in increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order.
Return the sorted array.
Example 1:
Input: nums = [1,1,2,2,2,3] Output: [3,1,1,2,2,2] Explanation: '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3
class Solution {
public int[] frequencySort(int[] nums) {
Map<Integer,Integer> freqCount = new HashMap<>();
for(int num : nums){
freqCount.put(num,freqCount.getOrDefault(num,0)+1);
}
Integer[] box = Arrays.stream(nums).boxed().toArray(Integer[]::new);
Arrays.sort(box,(a,b) -> {
int freqA = freqCount.get(a);
int freqB = freqCount.get(b);
if(freqA != freqB){
return freqA - freqB;
}else{
return b - a;
}
});
for(int i =0 ; i<nums.length;i++){
nums[i] = box[i];
}
return nums;
}
}
.
Comments
Post a Comment