leetcode

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

majority-element-ii.dart (921B)


      1 //Given a list of nums return all values that make up at least
      2 //1/3 of the elements in the list. The time complexity of this code 
      3 //is O(n) where n is the number of values in the nums list.
      4 //My solution iterates through the list placing the values into a hashmap
      5 //along with how many times the value has been found in the list.
      6 //Then from there it iterates through the map and adds any values
      7 //that occur more than 1/3 of the time in the list.
      8 //Time: 290ms Beats: 100%
      9 //Memory: 144.9MB Beats: 85.71%
     10 
     11 class Solution {
     12   List<int> majorityElement(List<int> nums) {
     13       Map<int, int> usages = {};
     14       for(int i = 0 ; i < nums.length ; ++i){
     15           usages[nums[i]] = (usages[nums[i]] ?? 0) + 1;
     16       }
     17       List<int> return_list = [];
     18       for(var entry in usages.entries){
     19         if(entry.value > nums.length / 3 ){
     20           return_list.add(entry.key);
     21         }
     22       }
     23       return return_list;
     24   }
     25 }