1636 Sort Array by Increasing Frequency
Вставка
- Опубліковано 6 вер 2024
- 1636 Sort Array by Increasing Frequency. - This Java code does these three things, It sorts the array based on increasing frequency of the values.
For values with the same frequency, it sorts them in decreasing order.
It handles both positive and negative numbers within the given constraints.
here is how it works:
1. We use a HashMap (frequencyMap) to count the frequency of each number in the input array.
2. We create a list of unique numbers from the keys of the frequency map.
3. We sort this list of unique numbers based on two criteria:
Primary: Increasing order of frequency
Secondary: For numbers with the same frequency, we sort in decreasing order of the numbers themselves
4. Finally, we create the result array by adding each number from our sorted list of unique numbers, repeating each number according to its frequency.
The time complexity is O(n log n) due to the sorting step, where n is the number of unique elements in the input array. The space complexity is O(n) for storing the frequency map and the list of unique numbers. thanks for watching and please subscribe.