two-sumV2.dart (812B)
1 //Doing this again to get more comfortable with maps. 2 //Also, using ?? -1 means that if the first val is null then return the value 3 //of -1 4 5 //Runtime: 320ms Beats: 72.49% 6 //Memory: 143.7MB Beats 36.55% 7 8 void main(){ 9 Solution sol = new Solution(); 10 List<int> l1 = [0,2,2,3,4,5,6,7,8,65,3,2,3,4,5,3,2,5,78,7,4,3,2,4,6,7,8,8,8,989,9,9,6,642,6,456,456,45,6,3456,45,6,3465]; 11 int target = 10; 12 print(sol.twoSum(l1,target)); 13 } 14 15 class Solution { 16 List<int> twoSum(List<int> nums, int target) { 17 18 Map<int, int> vals = {}; 19 for(int i = 0 ; i < nums.length ; ++i){ 20 int diff = target - nums[i]; 21 if(vals.containsKey(diff)){ 22 return [vals[diff]?? -1, i]; 23 } 24 else{ 25 vals[nums[i]] = i; 26 } 27 } 28 return []; 29 } 30 31 32 }