leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

top-k-frequent-elements-v1.dart (1034B)


      1 //Find the k most freqently used elements in the nums list then
      2 //return them as a list. To do this I placed all the values
      3 //into a map and then associated an integer with them to track the number
      4 //of occurences each one had. Then from there I went through the map k times
      5 //picking out the one with the most usages and placing it in the return list.
      6 //Time: 350ms Beats: 27.8%
      7 //Memory: 176.1MB Beats: 6.25%
      8 
      9 class Solution {
     10   List<int> topKFrequent(List<int> nums, int k) {
     11       Map<int,int> vals = {};
     12       List<int> return_list = [];
     13       for(int i = 0 ; i < nums.length ; ++i){
     14           vals[nums[i]] = (vals[nums[i]] ?? 0) + 1;
     15       }
     16       for(int i = 0 ; i < k ; ++i){
     17         int current_max = 0;
     18         int current_val = 0;
     19         for(var entry in vals.entries){
     20           if(entry.value > current_max){
     21             current_max = entry.value;
     22             current_val = entry.key;
     23           }
     24         }
     25         return_list.add(current_val);
     26         vals.remove(current_val);
     27       }
     28       return return_list;
     29   }
     30 }