给定两个数组 nums1 和 nums2 ,返回 它们的交集 。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序 。
示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]
示例 2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
解释:[4,9] 也是可通过的
【解题思路】将两个数组分别排序,对于nums1中每次新出现的数字,如果num2中有相同的数字,加入ans数组。在num2中找的数字大于num1中的数字,则退出num2中的搜索,减少算法开支。
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int num1 = 99999;
int num2 = 99999;
ArrayList<Integer> ans = new ArrayList<Integer>();
for(int i = 0; i < nums1.length; i++)
{
if(nums1[i] != num1)
{
num1 = nums1[i];
num2 = 99999;
for(int j = 0; j < nums2.length; j++)
{
if(nums2[j] != num2)
{
num2 = nums2[j];
if(num2 == num1)
{
ans.add(num1);
}
else if(num2 > num1) break;
}
}
}
}
return ans.stream().filter(integer -> integer != null).mapToInt(i->i).toArray();
}
}
List<Integer> 转int[]
List<Integer> ans = new ArrayList<Integer>();
int[] newAns = ans.stream().filter(Integer -> Integer != null).mapToInt(i->i).toArray();