Leecode数据结构刷题记录第三天:350. 两个数组的交集 II

①:Hash(字典)
public static int[] Intersect(int[] nums1, int[] nums2) { var dict = new Dictionary<int, int>(); //数组1置为小数组,数组2置为大数组 if (nums1.Length > nums2.Length) { var temp = new int[0]; temp = nums1; nums1 = nums2; nums2 = temp; } for (int i = 0; i < nums2.Length; i++) { if (dict.ContainsKey(nums2[i])) { //自增对复杂数据结构也有效 dict[nums2[i]]++; } else { dict.Add(nums2[i], 1); } } var list = new List<int>(); for (int j = 0; j < nums1.Length; j++) { if (dict.ContainsKey(nums1[j]) && dict[nums1[j]] > 0) { dict[nums1[j]] -= 1; list.Add(nums1[j]); } } return list.ToArray(); }
②双指针+排序(速度较快,内存消耗少)
public static int[] Intersect2(int[] nums1, int[] nums2) { Array.Sort(nums1); Array.Sort(nums2); List<int> result = new List<int>(); int i = 0; int j = 0; while (true) { if (nums1[i] > nums2[j]) { j++; } else if(nums1[i] < nums2[j]) { i++; } else { result.Add(nums1[i]); i++;j++; } if (i == nums1.Length || j == nums2.Length) { break; } } return result.ToArray(); }
 
                    
                     
                    
                 
                    
                
 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号