Given an array of integers nums, sort the array in an increasing order based on the frequency of the values. If multiple values have the same frequency, sort them in decreasing order.
Example 1:
Input: nums = [1,1,2,2,2,3]
Output: [3,1,1,2,2,2]
Example 2:
Input: nums = [2,3,1,3,2]
Output: [1,3,3,2,2]
Example 3:
Input: nums = [-1,1,-6,4,5,-6,1,4,1]
Output: [5,-1,4,4,-6,-6,1,1,1]
Counter from the collections module to count the frequency of each element in nums.from collections import Counter
def frequencySort(nums):
# Step 1: Count the frequency of each number
freq = Counter(nums)
# Step 2: Sort based on custom logic
nums.sort(key=lambda x: (freq[x], -x))
return nums
# Example Usage
print(frequencySort([1,1,2,2,2,3])) # Output: [3,1,1,2,2,2]
print(frequencySort([2,3,1,3,2])) # Output: [1,3,3,2,2]
print(frequencySort([-1,1,-6,4,5,-6,1,4,1])) # Output: [5,-1,4,4,-6,-6,1,1,1]
nums, as we iterate through the list once to count frequencies.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?