leetcode 349:兩個陣列的交集I
阿新 • • 發佈:2019-02-19
Problem:
Given two arrays, write a function to compute their intersection.
中文:已知兩個陣列,寫一個函式來計算它們的交集
Example:
Given
nums1 = [1, 2, 2, 1], nums2 = [2, 2]
,return[2, 2].
已知
nums1 = [1, 2, 2, 1], nums2 = [2, 2]
, return[2, 2].
Note:
- Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
(每個元素出現的次數與原來兩個陣列中重複的次數相同)
- (陣列的元素可以是任意順序的)
Follow up:
- What if the given array is already sorted? How would you optimize your algorithm?
- What if nums1’s size is small compared to num2’s size? Which algorithm is better?
- What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
- 假如已知的陣列是有序的該如何優化演算法?
- 假如陣列1的大小比陣列2要小該如何優化?
- 假如陣列2的元素在磁碟上是排序好的,但是記憶體不能一次性容納這些元素,該怎麼做?
Solution:
Analysis:
- 1.直接的想法:直接巢狀遍歷兩個陣列,遇到相同元素的就加入一個預定義好的陣列中。
- 預定義的陣列長度是陣列1和陣列2中較小的一個。
- 最後將該陣列有效的元素重新移植到新的一個數組中。
- 2.修正1:得到的陣列可能有很多重複的元素。
- 要再新增新元素到陣列中時檢查陣列中是否已經存在該元素。
- 陣列會越界,所以要在新增前檢查元素個數是否超過了陣列長度。
Code in JAVA
public static int[] intersection(int[] a1, int[] a2) {
int n = Math.min(a1.length, a2.length);
int[] is = new int[n];
int count = 0;
for(int i = 0; i < a1.length; i++){
int tmep = a1[i];
for(int j = 0; j < a2.length; j++){
if(tmep == a2[j]){
boolean exist = false;
for(int k = 0; k < count; k++){
if(is[k] == tmep){
exist = true;
break;
}
}
if(count >= n){
break;
}
if(!exist){
is[count] = tmep;
count++;
}
break;
}
}
}
int[] itersection = new int[count];
for(int i = 0; i < count; i++){
itersection[i] = is[i];
}
return itersection;
}