2020.7.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 }
题目思路:
遍历数组1,将每个数字的个数存储到哈希表中;遍历数组2,将对应数字的各种-1,判断个数,满足条件将数值添加入数组中,最后利用copyOfRange方法返回最终结果。
时间复杂度:O(m+n)
空间复杂度:O(m)
题后总结:
优:运用了哈希表存储,减小了搜索时间,使用了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))
总体思路,对数组排序后,利用双指针遍历两个数组,根据判断的大小情况,进行指针的移动。