Sort Array by Increasing Frequency
Approach\nStep 1: Counting Frequencies\n\nPurpose: This step counts the frequency of each element in the nums array using a HashMap. The key of the map is the e
# Approach\nStep 1: Counting Frequencies\n\nPurpose: This step counts the frequency of each element in the nums array using a HashMap. The key of the map is the element itself, and the value is the frequency of that element.\n\nExplanation:\nLoop through each element in the nums array.\nIf the element is already present in the map, increment its count by 1.\nIf the element is not present, add it to the map with a frequency of 1.\n\nStep 2: Creating a List of Unique Numbers\n\nPurpose: Create a list of unique numbers from the keys of the frequency map. This list will be sorted based on the required criteria.\n\nExplanation:\nThe keySet() method of the map returns a set of all keys, which are the unique numbers in the array.\nThis set is used to initialize an ArrayList, allowing us to sort the unique numbers later.\n\nStep 3: Sorting the List\nPurpose: Sort the list of unique numbers based on their frequency, with ties broken by sorting in decreasing order.\n\nExplanation:\nThe Collections.sort() method is used with a custom comparator to define the sorting behavior.\nComparator Logic:\nIf the frequencies of two numbers a and b are equal (map.get(a) == map.get(b)), sort them in descending order (b - a).\nOtherwise, sort them in ascending order of their frequency (map.get(a) - map.get(b)).\n\nStep 4: Constructing the Result Array\n\nPurpose: Construct the final sorted array based on the sorted list of unique numbers and their frequencies.\n\nExplanation:\nAn array result of the same length as nums is created to store the final sorted elements.\nLoop through each number in the sorted list.\nFor each number, append it to the result array according to its frequency stored in the map.\nIncrement the index variable to fill the result array correctly.\n\n\n# Code\n```\nclass Solution {\n    public int[] frequencySort(int[] nums) {\n        Map<Integer, Integer> map=new HashMap<Integer, Integer>();\n          for(int i=0;i<nums.length;i++){\n            if(map.containsKey(nums[i])){\n                map.put(nums[i],map.get(nums[i])+1);\n            }\n            else{\n                map.put(nums[i],1);\n            }\n          }\n\n          List<Integer> list=new ArrayList<Integer>(map.keySet());\n          Collections.sort(list,(a,b)->{\n             if(map.get(a)==map.get(b)){\n                return b - a;\n             }\n             else{\n                return map.get(a) - map.get(b);\n             }\n            });\n        int[] result=new int[nums.length];\n        int index=0;\n        for(int num:list){\n            for(int i=0;i<map.get(num);i++){\n                result[index++]=num;\n            }\n        }\n        return result;\n    }\n}\n```\n
['Java']