LeetCode349 两个数组的交集

两个数组的交集

题目链接:LeetCode349
描述
给定两个数组 nums1 和 nums2 ,返回它们的 交集。输出结果中的每个元素一定是唯一的。我们可以不考虑输出结果的顺序 。

示例

输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
解释:[4,9] 也是可通过的

思路

注意,使用数组来做哈希的题目,是因为题目都限制了数值的大小。
而这道题目没有限制数值的大小,就无法使用数组来做哈希表了。

代码
方法一:使用Hash数组

class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
int[] nums = new int[1001];
for(int num1 : nums1){
nums[num1] = 1;
}
for(int num2 : nums2){
nums[num2] = nums[num2]+nums[num2];
}
List<Integer> list = new ArrayList<>();
for(int i=0; i<1001; i++){
if(nums[i] > 1){
list.add(i);
}
}
int index = 0;
int res[] = new int[list.size()];
for(int i : list){
res[index++] = i;
}
return res;
}
}

方法二:使用HashSet

class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if(nums1.length == 0 || nums2.length == 0){
return new int[0];
}
Set<Integer> set = new HashSet<>();
Set<Integer> reSet = new HashSet<>();
for(int i : nums1){
set.add(i);
}
for(int i : nums2){
if(set.contains(i)){
reSet.add(i);
}
}
return reSet.stream().mapToInt(x -> x).toArray();
}
}
posted @   dwhere  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示