Beats 100% || Explained with Intuition and Diagram || 0ms
Intuition\n Describe your first thoughts on how to solve this problem. \nGiven the constraints -100 <= nums[i] <= 100, you can count the frequency of elements u
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGiven the constraints -100 <= nums[i] <= 100, you can count the frequency of elements using an array where the index represents the value shifted by 100 (i.e., freq[x + 100] for x in nums). Then, sort it using a lambda function, which is efficient in both C++ and Python.\n\nA similar concept can be applied using the Counter class in Python for a one-liner solution, which is slower but acceptable.\n\nAnother approach involves using counting sort, which reduces the time complexity to O(n + m).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCount the frequency of elements using freq[x + 100] for x in nums. Sort nums with respect to the lambda function [&](int x, int y){ return (freq[x + 100] == freq[y + 100]) ? x > y : freq[x + 100] < freq[y + 100]; }.\n\nThe second approach uses counting sort, which is more complex compared to the simpler methods. While it has a linear time complexity, it doesn\'t provide significant benefits for small test cases. The best performance recorded is 2ms.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlogn)\nCounting sort: O(n+m)\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(m) where m=max(nums)\n\n# Code\n```\nclass Solution {\npublic:\n    using int2=array<int,2>;\n    vector<int> frequencySort(vector<int>& nums) {\n        int n=nums.size(), freq[201]={0};\n        for(int x:nums){\n            freq[x+100]++;\n        }\n        \n        sort(nums.begin(), nums.end(), [&](int x, int y){\n            return (freq[x+100]==freq[y+100])?x>y:freq[x+100]<freq[y+100];\n        });\n        return nums;\n    }\n};\n\n\n\n\n```
['C++']