/*
349. 两个数组的交集
给定两个数组 nums1 和 nums2 ,返回 它们的交集 。
输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序 。
*/
/*
使用排序+双指针的方式处理
*/
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);//先把两个数组进行排序(默认快排)
int index1 = 0, index2 = 0, index = 0;
int len1 = nums1.length, len2 = nums2.length;
int[] ans = new int[len1 + len2];//定义一个数组接收答案(长度设置为两个数组长度之和)
while (index1 < len1 && index2 < len2) {
if (nums1[index1] == nums2[index2]) {//如果元素相等,一定会后移指针
if (index == 0 || nums1[index1] != ans[index - 1]) {//保证不放入相同的元素
ans[index] = nums1[index1];
index++;
}
index1++;
index2++;
} else if (nums1[index1] < nums2[index2]) {//元素不相等,根据大小移动两个数组的指针
index1++;
} else {
index2++;
}
}
return Arrays.copyOfRange(ans,0,index);//最后返回一个子数组,后面的0元素都不要了
}
}
代码随想录leetcode刷题Day08-哈希表
最新推荐文章于 2024-07-10 16:47:58 发布