2020.7.13 力扣每日
阿新 • • 發佈:2020-07-13
1 public static int[] intersect(int[] nums1, int[] nums2) { 2 int len1 = nums1.length, len2 = nums2.length, index = 0; 3 int[] res = new int[len1 < len2 ? len1 : len2]; 4 Map<Integer, Integer> num = new HashMap<Integer, Integer>(); 5 for (int i = 0; i < len1; i++) {6 num.put(nums1[i], num.getOrDefault(nums1[i], 0) + 1); 7 } 8 for (int i = 0; i < len2; i++) { 9 num.put(nums1[i], num.getOrDefault(nums1[i], 0) - 1); 10 if (num.get(nums2[i]) > -1) { 11 res[index++] = nums2[i]; 12 }13 } 14 return Arrays.copyOfRange(res, 0, 2); 15 }
時間複雜度:O(m+n)
空間複雜度:O(m)
題目思路:遍歷陣列1,將每個數字的個數儲存到雜湊表中;遍歷陣列2,將對應數字的各種-1,判斷個數,滿足條件將數值新增入陣列中,最後利用copyOfRange方法返回最終結果。
題後總結 優:運用了雜湊表儲存,減小了搜尋時間,使用了getOrDefault,減少了程式碼量。
差:在遍歷陣列2時,無需每次都put新值,這樣增加了時間,可以直接利用getOrDefault返回值進行判斷,若>0,再進行put操作。遍歷時可以取陣列較短者,空間複雜度能縮小為 O(min(m,n));
本題還有利用雙指標的方法進行解答,
1 public static int[] intersect(int[] nums1, int[] nums2) { 2 Arrays.sort(nums1); 3 Arrays.sort(nums2); 4 int len1 = nums1.length, len2 = nums2.length; 5 int[] res = new int[Math.min(len1, len2)]; 6 int index1 = 0, index2 = 0, index = 0; 7 while (index1 < len1 && index2 < len2) { 8 if (nums1[index1] < nums2[index2]) { 9 index1++; 10 } else if (nums1[index1] > nums2[index2]) { 11 index2++; 12 } else { 13 res[index] = nums1[index1]; 14 index1++; 15 index2++; 16 index++; 17 } 18 } 19 return Arrays.copyOfRange(res, 0, index); 20 }
時間複雜度:O(m*log m+n*log n)空
空間複雜度:O(min(m,n))
總體思路,對陣列排序後,利用雙指標遍歷兩個陣列,根據判斷的大小情況,進行指標的移動。