Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2]
Example 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.
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?
根据这个题目比较简单,有多种解法:
1.利用map的原理:
思路先将一个数组存储到map当中,该元素作为key关键字,元素出现的次数作为它的value值。
private int[] intersect1(int[] arr1, int[] arr2) {
if (arr1.length == 0 || arr2.length == 0) {
return new int[]{};
}
HashMap<Integer, Integer> map = new HashMap<>();
for (int num1 : arr1) {
if (!map.keySet().contains(num1)) {
map.put(num1, 1);
} else {
map.put(num1, map.get(num1) + 1);
}
}
ArrayList<Integer> list = new ArrayList<>();
for (int num2 : arr2) {
if (map.keySet().contains(num2) && map.get(num2) > 0) {
list.add(num2);
map.put(num2, map.get(num2) - 1);
}
}
int[] newArr = new int[list.size()];
for (int index = 0; index < list.size(); index++) {
newArr[index] = list.get(index);
}
return newArr;
}
时间复杂度:O(n);
空间复杂度:O(n);
2.直接利用指针的方式实现:其中在使用指正有两种方式
2.1,利用压缩数组,把数组中不相等的数去掉
private int[] intersect3(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0;
int j = 0;
int count = 0;
int flag = 0;
while (i < nums1.length - flag && j < nums2.length) {
if (nums1[i] < nums2[j]) {
for (int k = i; k < nums1.length - 1; k++) {
nums1[k] = nums1[k + 1];
}
flag++;
} else if (nums1[i] > nums2[j]) {
j++;
} else {
count++;
i++;
j++;
}
}
return Arrays.copyOfRange(nums1, 0, count);
}
时间复杂度:O(n^2)
空间复杂度:O(1)
2.2 利用复制法,把相等的元素复制到数组头部,最后把它全部复制过来;
private int[] intersect5(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0;
int j = 0;
int k = 0;
while (i < nums1.length && j < nums2.length) {
if (nums1[i] > nums2[j]) {
j += 1;
continue;
}
if (nums1[i] < nums2[j]) {
i += 1;
continue;
}
nums1[k]=nums1[i];
k += 1;
j += 1;
i += 1;
}
return Arrays.copyOfRange(nums1, 0, k);
}
时间复杂度:O(n*logn)
空间复杂度:O(1)