sort-array-by-increasing-frequency.dart (1907B)
1 //Given a list of nums sort it by the number 2 //of occurences a given integer has in the list. 3 //If two integers have the same number of occurences 4 //then place them in the return list in reverse order 5 //based on the integer value. 6 7 //To solve this I created a hashmap to find the frequency 8 //of each value in the list. Then from there I iterated through 9 //that list to flip the places of the keys and values so 10 //the number of occurences becomes the key and the values 11 //that occur tht often are the values. Then from there I got 12 //a list of all possible lengths and sorted it. Using this I 13 //took the lists out of the map and placed them into the return list 14 //making sure to retain the frequency of values in the new list(i.e. if there were 3 2's originally there should return 3 2's). 15 16 //Time: 294ms Beats: 100% 17 //Memory: 148.7MB Beats: 60% 18 19 class Solution { 20 List<int> frequencySort(List<int> nums) { 21 Map<int,int> num_frequency = {}; 22 for(int _num in nums){ 23 num_frequency[_num] = (num_frequency[_num] ?? 0) + 1; 24 } 25 Map<int,List<int>> frequencies = {}; 26 for(var entry in num_frequency.entries){ 27 List<int> current = (frequencies[entry.value] ?? []); 28 current.add(entry.key); 29 frequencies[entry.value] = current; 30 } 31 List<int> frequency_opts = frequencies.keys.toList(); 32 List<int> return_list = []; 33 frequency_opts.sort(); 34 for(int i = 0 ; i < frequency_opts.length ; ++i){ 35 int current_freq = frequency_opts[i]; 36 List<int> vals_of_freq = (frequencies[current_freq] ?? []); 37 vals_of_freq.sort(); 38 vals_of_freq = vals_of_freq.reversed.toList(); 39 for(int x = 0 ; x < vals_of_freq.length ; ++x){ 40 for(int z = 0 ; z < current_freq ; ++z){ 41 return_list.add(vals_of_freq[x]); 42 } 43 } 44 } 45 return return_list; 46 } 47 }