题目:
给定两个数组,写一个函数来计算它们的交集。
注意:
结果中的每个元素的出现次数应该与它在两个数组中显示的次数相同。
结果可以是任意顺序的。
Given two arrays, write a function to compute their intersection.
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2]
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9]
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
方法:
先对数组进行排序,对排好序的数组进行操作
如果相同,则同时往后挪一位;如果不同,则将更小的数往后挪一位;
相同的数加入到ArrayList中,最后转成int[]
代码:
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
List<Integer> interList = new ArrayList<Integer>();
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0,j = 0;
while(i<nums1.length&&j<nums2.length){
if(nums1[i] == nums2[j]){
interList.add(nums1[i]);
i++;
j++;
}else if(nums1[i]>nums2[j]){
j++;
}else{
i++;
}
}
int[] interArray = new int[interList.size()];
Iterator it = interList.iterator();
i=0;
while(it.hasNext()){
interArray[i]=(Integer)(it.next());
i++;
}
return interArray;
}
}
扩展问题:
如果给定的数组已经排序了怎么办?如何优化算法?
如果nums1的大小比nums2的小怎么办?哪种算法更好?
如果nums2的元素存储在磁盘上,并且内存有限,以至于不能一次将所有元素加载到内存中,该怎么办?
——可以将nums1的元素存在hashmap中,结构为数-次数,再依次对nums2中的元素进行判断,存在则加入到reList中并且对次数减1
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 nums2'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?