leetcode

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

contains-duplicateV2.dart (941B)


      1 //This is a better solution to the problem. 
      2 //find any repeating integers in the list where
      3 //the absolute value of the index is less than or equal to 
      4 //k. To do this I added previous values to a map and checked them with
      5 //the newest one. If they meet the k rule then it returns true otherwise the
      6 //old value gets replaced. The time complexity of this code is O(n) where n is 
      7 //the length of the nums list. 
      8 //Time: 401ms Beats: 38.46%
      9 //Memory: 199.3MB Beats: 7.69%
     10 
     11 class Solution {
     12   bool containsNearbyDuplicate(List<int> nums, int k) {
     13       Map<int,int> previous_vals = {};
     14       for(int i = 0 ; i < nums.length ; ++i){
     15           if(previous_vals[nums[i]] == null){
     16               previous_vals[nums[i]] = i;
     17           }
     18           else if(((previous_vals[nums[i]] ?? 0) - i).abs() <= k){
     19               return true;
     20           }
     21           else{
     22               previous_vals[nums[i]] = i;
     23           }
     24       }
     25       return false;
     26   }
     27 }