LC-349
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
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]
Explanation: [4,9] is also accepted.
Constraints:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/intersection-of-two-arrays
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
-
单纯API去重
-
排序 + 双指针
如果两个数组是有序的,则可以使用双指针的方法得到两个数组的交集。
首先对两个数组进行排序,然后使用两个指针遍历两个数组。
可以预见的是加入答案的数组的元素一定是递增的,为了保证加入元素的唯一性,我们需要额外记录变量 pre 表示上一次加入答案数组的元素。
初始时,两个指针分别指向两个数组的头部。
每次比较两个指针指向的两个数组中的数字,
如果两个数字不相等,则将指向较小数字的指针右移一位,如果两个数字相等,且该数字不等于 pre ,将该数字添加到答案并更新pre 变量,同时将两个指针都右移一位。
当至少有一个指针超出数组范围时,遍历结束。
Java实现
package LC.hash;
import java.util.HashSet;
import java.util.Set;
public class LC349 {
public static void main(String[] args) {
int[] nums1 = {1, 2, 2, 1};
int[] nums2 = {2, 2};
int[] res = intersection(nums1, nums2);
for (int item :
res) {
System.out.println(item + ",");
}
}
/**
* API战士
* @param nums1
* @param nums2
* @return
*/
public static int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
//利用HashSet去重
for (int i : nums1) {
set1.add(i);
}
//set2 里面已经是交集
for (int i : nums2) {
if (set1.contains(i)) {
set2.add(i);
}
}
//最后return是 数组形式
int[] arr = new int[set2.size()];
int j = 0;
for (int i : set2) {
arr[j++] = i;
}
return arr;
}
}
Python实现
from typing import List
class Solution:
def intersection(self: List[int], nums2: List[int]) -> List[int]:
self.sort()
nums2.sort()
length1, length2 = len(self), len(nums2)
res = list()
index1 = index2 = 0
while index1 < length1 and index2 < length2:
num1 = self[index1]
num2 = nums2[index2]
if num1 == num2:
# 保证加入元素的唯一性
if not res or num1 != res[-1]:
res.append(num1)
index1 += 1
index2 += 1
elif num1 < num2:
index1 += 1
else:
index2 += 1
return res
int_nums1 = [1, 2, 2, 1]
int_nums2 = [2, 2]
print(Solution.intersection(int_nums2, int_nums2))
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能