difference-of-two-arrays.dart (1033B)
1 //Find all unique values that appear in one list but not the other 2 //then return the unique values as two lists. 3 //I used a hashmap for this when I should have used a set because 4 //I only need to know unique values and not how many of each there are. 5 //The time complexity of this code is O(n + k) where n is the number of elements 6 //in the first list and k is the number in the second. 7 //Time: 375ms Beats: 30% 8 //Memory: 150.5MB Beats: 60% 9 10 class Solution { 11 List<List<int>> findDifference(List<int> nums1, List<int> nums2) { 12 Map<int , int> map1 = {}; 13 Map <int, int> map2 = {}; 14 for(int i = 0 ; i < nums1.length ; ++i){ 15 map1[nums1[i]] = (map1[nums1[i]] ?? 0) + 1; 16 } 17 for(int i = 0 ; i < nums2.length ; ++i){ 18 map2[nums2[i]] = 1; 19 } 20 for(int i = 0 ; i < nums1.length ; ++i){ 21 map2.remove(nums1[i]); 22 } 23 for(int i = 0 ; i < nums2.length ; ++i){ 24 map1.remove(nums2[i]); 25 } 26 27 return [map1.keys.toList() , map2.keys.toList()]; 28 } 29 }