http://www.lintcode.com/en/problem/intersection-of-two-arrays/
题目:求两数组的交集(两数组长度分别为m,n),不包含重复元素
方法一:Hash
时间复杂度 O(n + m) 空间复杂度 O(min(m, n))
解答:将第一个数组的元素存入HashSet, 遍历第二个数组若有元素存在于HashSet中,将此元素存入temp set中。最后将tempSet中的元素转化为题目所需返回数组的形式;
第一次犯错:给结果数组分配了min(m, n)的空间,没有用到的位置会被自动填充0元素导致结果错误。应先用HashSet动态存储结果,最后进行转化即可;
代码:
public class Solution {
/**
* @param nums1 an integer array
* @param nums2 an integer array
* @return an integer array
*/
public int[] intersection(int[] nums1, int[] nums2) {
// Write your code here
if (nums1 == null || nums2 == null) {
return null;
}
int len1 = nums1.length;
int len2 = nums2.length;
Set<Integer> set = new HashSet<Integer>();
Set<Integer> temp = new HashSet<Integer>();
for (int i = 0; i < len1; i++) {
set.add(nums1[i]);
}
for (int j = 0; j < len2; j++) {
if (!set.contains(nums2[j])) {
temp.add(nums2[j]);
}
}
int[] res = new int[temp.size()];
int index = 0;
for (Integer i : temp) {
res[index] = i;
index++;
}
return res;
}
}
方法二:Merge two sorted arrays
时间复杂度O(nlogn + mlogm) 空间复杂度O(1)
解答:将两个数组排序后,分别从两个数组中最小元素开始依次比较,相同的元素存入temp(注意不可重复),最后将temp转化为固定长度的结果数组(去除未赋值的0元素);
备注:也可以将num1排序后,遍历num2中所有元素,依次用二分法在num1中寻找,时间复杂度为O(nlogn + mlogn),空间复杂度不变
代码:
public class Solution {
/**
* @param nums1 an integer array
* @param nums2 an integer array
* @return an integer array
*/
public int[] intersection(int[] nums1, int[] nums2) {
// Write your code here
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0;
int j = 0;
int index = 0;
int[] temp = new int[nums1.length];
while (i < nums1.length && j < nums2.length) {
if (nums1[i] == nums2[j] && (index == 0 || nums1[i] != temp[index - 1])) {
temp[index++] = nums1[i];
} else if (nums1[i] < nums2[j]) {
i++;
} else {
j++;
}
}
int[] res = new int[index];
for (int k = 0; k < index; k++) {
res[k] = temp[k];
}
return res;
}
}
方法三:Binary Search(二分法排序)
时间复杂度O(nlogn + mlogm) 空间复杂度O(1) 适用于 m >> n的情况
相当于在num1数组中依次寻找num2中的每个元素。方法与 Search in rotated sorted array类似。