/*
* @lc app=leetcode.cn id=349 lang=java
*
* [349] 两个数组的交集
*/
// @lc code=start
class Solution {
/**
* Hash检测法
* 57/57 cases passed (3 ms)
Your runtime beats 49.51 % of java submissions
Your memory usage beats 63.84 % of java submissions (42.3 MB)
*/
// public int[] intersection(int[] nums1, int[] nums2) {
// HashSet<Integer> set = new HashSet<>();
// for(int ele : nums1){
// set.add(ele);
// }
// List<Integer> ans = new ArrayList<>((int)Math.min(nums1.length, nums2.length));
// for(int ele : nums2){
// Integer eleObj = ele;
// if(!set.remove(eleObj)){
// continue;
// }
// ans.add(eleObj);
// }
// int[] ansArr = new int[ans.size()];
// for(int i = 0; i < ansArr.length; i++){
// ansArr[i] = ans.get(i);
// }
// return ansArr;
// }
/**
* 排序法
* 57/57 cases passed (2 ms)
Your runtime beats 87.98 % of java submissions
Your memory usage beats 96.07 % of java submissions (42 MB)
*/
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
List<Integer> ans = new ArrayList<>((int)Math.min(nums1.length, nums2.length));
{
int i = 0, j = 0;
int preEle = -1;
while(i < nums1.length && j < nums2.length){
int ele1 = nums1[i];
if(ele1 < nums2[j]){
i++;
continue;
}
if(ele1 > nums2[j]){
j++;
continue;
}
i++;
j++;
if(ele1 == preEle){
continue;
}
ans.add(ele1);
preEle = ele1;
}
}
int[] ansArr = new int[ans.size()];
for(int i = 0; i < ansArr.length; i++){
ansArr[i] = ans.get(i);
}
return ansArr;
}
}
// @lc code=end
08-16
322
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-20
205
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-20
670
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
04-29