題目
給定兩個數組,寫一個方法來計算它們的交集。
例如:
給定nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, 返回 [2, 2]
.
注意:
- 輸出結果中每個元素出現的次數,應與元素在兩個數組中出現的次數一致。
- 我們可以不考慮輸出結果的順序。
跟進:
- 如果給定的數組已經排好序呢?你將如何優化你的算法?
- 如果
nums1
的大小比nums2
小很多,哪種方法更優? - 如果
nums2
的元素存儲在磁盤上,內存是有限的,你不能一次加載所有的元素到內存中,你該怎麼辦?
解法1
https://github.com/biezhihua/LeetCode
用Map
來建立nums1
中字符和其出現個數之間的映射, 然後遍歷nums2
數組,如果當前字符在Map
中的個數大於0,則將此字符加入結果res
中,然後Map
的對應值自減1。
public int[] intersect(int[] nums1, int[] nums2) {
List<Integer> tmp = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums1.length; i++) {
Integer value = map.get(nums1[i]);
map.put(nums1[i], (value == null ? 0 : value) + 1);
}
for (int i = 0; i < nums2.length; i++) {
if (map.containsKey(nums2[i]) && map.get(nums2[i]) != 0) {
tmp.add(nums2[i]);
map.put(nums2[i], map.get(nums2[i]) - 1);
}
}
int[] result = new int[tmp.size()];
int i = 0;
for (Integer e : tmp)
result[i++] = e;
return result;
}
解法2
給兩個數組排序,然後用兩個索引分別代表兩個數組的起始位置,如果兩個索引所代表的數字相等,則將數字存入結果中,兩個索引均自增1,如果第一個索引所代表的數字大,則第二個索引自增1,反之亦然。
public int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
List<Integer> tmp = new ArrayList<>();
int i = 0;
int j = 0;
while (i < nums1.length && j < nums2.length) {
if (nums2[j] > nums1[i]) {
i++;
} else if (nums2[j] < nums1[i]) {
j++;
} else {
tmp.add(nums1[i]);
i++;
j++;
}
}
int[] result = new int[tmp.size()];
for (int k = 0; k < result.length; k++) {
result[k] = tmp.get(k);
}
return result;
}