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]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.Comparator;import java.util.HashMap;import java.util.List;public class SortArrayByIncreasingFrequency {public static void main(String[] args) {int[] nums = { 1, 1, 2, 2, 2, 3 };int[] sorted = frequencySort(nums);System.out.println(Arrays.toString(sorted));}static public int[] frequencySort(int[] nums) {HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>();for (int i : nums) {mp.put(i, mp.getOrDefault(i, 0) + 1);}List<int[]> list = new ArrayList<int[]>();for (int key : mp.keySet()) {list.add(new int[] { mp.get(key), key });}// sorting based on conditionCollections.sort(list, new Comparator<int[]>() {@Overridepublic int compare(int[] o1, int[] o2) {if (o1[0] == o2[0]) {if (o1[1] > o2[1])return -1;elsereturn 1;} else {if (o1[0] < o2[0])return -1;elsereturn 1;}}});int arr[] = new int[nums.length];int i = 0;for (int j = 0; j < list.size(); j++) {int cnt = list.get(j)[0];while (cnt > 0) {arr[i++] = list.get(j)[1];cnt--;}}return arr;}}
C++
#include <bits/stdc++.h>using namespace std;static bool cmp(pair<int, int> a, pair<int, int> b){if (a.first == b.first)return a.second > b.second;return a.first < b.first;}vector<int> frequencySort(vector<int> &nums){map<int, int> mp;for (int i = 0; i < nums.size(); i++)mp[nums[i]]++;vector<pair<int, int>> v;for (int i = 0; i < nums.size(); i++)v.push_back({mp[nums[i]], nums[i]});sort(v.begin(), v.end(), cmp);vector<int> res;for (int i = 0; i < v.size(); i++)res.push_back(v[i].second);return res;}int main(){vector<int> nums = {1, 1, 2, 2, 2, 3};vector<int> sorted = frequencySort(nums);cout << "[";for (int i = 0; i < sorted.size() - 1; i++)cout << sorted[i] << ",";cout << sorted[sorted.size() - 1] << "]";return 0;}
No comments:
Post a Comment