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;
}