[LeetCode]兩個陣列的交集 II
阿新 • • 發佈:2018-11-22
[LeetCode]兩個陣列的交集 II
給定兩個陣列,寫一個方法來計算它們的交集。
例如:
給定* ***nums1 =[1, 2, 2, 1]
, nums2 =[2, 2]
, 返回[2, 2]
.注意:
- * * 輸出結果中每個元素出現的次數,應與元素在兩個陣列中出現的次數一致。
- 我們可以不考慮輸出結果的順序。
跟進:
- 如果給定的陣列已經排好序呢?你將如何優化你的演算法?
- 如果 nums1 的大小比 nums2 小很多,哪種方法更優?
- 如果nums2的元素儲存在磁碟上,記憶體是有限的,你不能一次載入所有的元素到記憶體中,你該怎麼辦?
public int[] intersect(int[] nums1, int[] nums2) {
int[] news = new int[0];
if (nums1 == null || nums2 == null) {
return null;
}
if (nums1.length == 0 || nums2.length == 0) {
return news;
}
news = new int[nums1.length];
int [] count = new int[nums1.length];
int index = 0;
for (int i = 0; i < nums2.length; i++) {
for (int j = 0; j < nums1.length; j++) {
if (nums1[j] == nums2[i] && count[j] == 0) {
news[index] = nums1[j];
index++;
count[j] = 1 ;
break;
}
}
}
int[] ints = new int[index];
for (int i = 0; i < ints.length; i++) {
ints[i] = news[i];
}
return ints;
}