题目:
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Note:
Each element in the result must be unique.
The result can be in any order.
本题使用查找表解决问题,将第一个数组存入Map中作为查找表,将第二个数组作为输入数据在查找表中查找
public class IntersectionTwoArrays {
public static int[] intersection(int[] nums1, int[] nums2) {
Map<Integer, Boolean> map = new HashMap<>();
List<Integer> list = new ArrayList<>();
for (int num : nums1) {
map.put(num, false);
}
for (int num : nums2) {
if (map.containsKey(num) && map.get(num) == false) {
list.add(num);
map.put(num,true);
}
}
int[] result = new int[list.size()];
int i=0;
for (Integer val : list) {
result[i++] = val;
}
return result;
}
public static void main(String[] args) {
int[] nums1 = {4,9,5};
int[] nums2 = {9,4,9,8,4};
System.out.println(Arrays.toString(intersection(nums1, nums2)));
}
}
LeetCode上时间1ms耗时答案
public class IntersectionTwoArrays {
public static int[] intersection(int[] nums1, int[] nums2) {
/*
Map<Integer, Boolean> map = new HashMap<>();
List<Integer> list = new ArrayList<>();
for (int num : nums1) {
map.put(num, false);
}
for (int num : nums2) {
if (map.containsKey(num) && map.get(num) == false) {
list.add(num);
map.put(num,true);
}
}
int[] result = new int[list.size()];
int i=0;
for (Integer val : list) {
result[i++] = val;
}
return result;
*/
Arrays.sort(nums1); // assume sorted
Arrays.sort(nums2); // assume sorted
int[] res = new int[Math.min(nums1.length, nums2.length)];
int resSize = 0;
int i = 0;
int j = 0;
while (i < nums1.length && j < nums2.length) {
int iVal = nums1[i];
int jVal = nums2[j];
if (iVal > jVal) {
while (j < nums2.length && jVal == nums2[j]) j++;
} else if (iVal < jVal) {
while (i < nums1.length && iVal == nums1[i]) i++;
} else { // equal
res[resSize++] = iVal;
while (i < nums1.length && iVal == nums1[i]) i++;
while (j < nums2.length && jVal == nums2[j]) j++;
}
}
return Arrays.copyOf(res, resSize);
}
public static void main(String[] args) {
int[] nums1 = {4,9,5};
int[] nums2 = {9,4,9,8,4};
System.out.println(Arrays.toString(intersection(nums1, nums2)));
}
}