349. Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2]
.
Note:
- Each element in the result must be unique.
- The result can be in any order.
解法1:
public int[] Intersection(int[] nums1, int[] nums2) { var hashtable = new HashSet<int>(); foreach(var n in nums1) { hashtable.Add(n); } var res = new List<int>(); foreach(var n in nums2 ) { if(hashtable.Contains(n) && !res.Contains(n)) { res.Add(n); } } return res.ToArray(); }
解法2:
public int[] Intersection(int[] nums1, int[] nums2) { var res = new List<int>(); Array.Sort(nums1); Array.Sort(nums2); int size1 = nums1.Count(); int size2 = nums2.Count(); int i = 0; int j = 0; int lastNumber =0; while(i<size1 && j<size2) { if(nums1[i] == nums2[j]) { if(res.Count()==0 || nums1[i] != res[res.Count()-1]) res.Add(nums1[i]); i++; j++; } else if(nums1[i] < nums2[j]) { i++; } else { j++; } } return res.ToArray(); }