问题:数组
Given two arrays, write a function to compute their intersection.spa
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2]
.指针
Note:code
解决:element
①使用hashSet保存nums1数组中的值,而后比较便可。耗时5ms.rem
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
List<Integer> list = new ArrayList<>();
Set<Integer> set = new HashSet<>();
for (int n : nums1) {
set.add(n);
}
for (int n : nums2) {
if (set.contains(n)) {
list.add(n);
set.remove(n);
}
}
int res[] = new int[list.size()];
for(int i = 0;i < list.size();i ++ ){
res[i] = list.get(i);
}
return res;
}
}get
②使用双指针法, 使用一个临时数组保存相同的数值,当扫描时存在与临时数组最后一个值相同的数时,跳过,不然,添加到临时数组中。hash
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) return new int[0];
Arrays.sort(nums1);
Arrays.sort(nums2);
int temp[] = new int[nums1.length];
int p1 = 0;
int p2 = 0;
int p = 0;
while(p1 < nums1.length && p2 < nums2.length){
if (nums1[p1] == nums2[p2]) {
if (p - 1 >= 0 && temp[p - 1] == nums1[p1]) {//相同的值重复
//什么都不作
}else{
temp[p] = nums1[p1];
p ++;
}
p1 ++;
p2 ++;
}else if (nums1[p1] < nums2[p2]) {
p1 ++;
}else{
p2 ++;
}
}
int res[] = new int[p];
for (int i = 0;i < p ;i ++ ) {
res[i] = temp[i];
}
return res;
}
}it