給定兩個數組,寫一個方法來計算它們的交集
注意:
- 輸出結果中每個元素出現的次數,應與元素在兩個數組中出現的次數一致。
- 我們可以不考慮輸出結果的順序。
跟進:
- 如果給定的數組已經排好序呢?你將如何優化你的算法?
- 如果 nums1 的大小比 nums2 小很多,哪種方法更優?
- 如果nums2的元素存儲在磁盤上,內存是有限的,你不能一次加載所有的元素到內存中,你該怎麼辦?
一: 給定 nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, 返回 [2]
.
Solution:
public int[] intersect_2(int[] nums1, int[] nums2) {//不考慮重複
Set<Integer> s2 = new HashSet<>();
Set<Integer> result = new HashSet<>();
for(int i = 0; i< nums2.length; i++){
s2.add(nums2[i]);
}
System.out.println("s2.size():"+s2.size());
for(int j = 0; j<nums1.length; j++){
if(s2.contains(nums1[j])){
result.add(nums1[j]);
}
else
continue;
}
int[] a = new int[result.size()];
int i = 0;
for(int x: result){
a[i] = x;
i++;
}
return a;
}
二:給定 nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, 返回 [2, 2]
.
Solution二:
public int[] intersect(int[] nums1, int[] nums2) {//考慮重複
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0;
int j = 0;
List<Integer> l1 = new ArrayList<>();
while(i < nums1.length && j < nums2.length){
if(nums1[i] > nums2[j] ){
j++;
}
else if(nums1[i] < nums2[j]){
i++;
}
else{
l1.add(nums1[i]);
i++;
j++;
}
}
int[] a = new int[l1.size()];
int y = 0;
for(int x:l1){
a[y] = x;
y++;
}
return a;
}