【题目描述】
给定两个数组 nums1
和 nums2
,返回 它们的交集 唯一 的。我们可以 不考虑输出结果的顺序 。
https://leetcode.cn/problems/intersection-of-two-arrays/
【示例】
【代码】admin
思路:2个循环
package com.company;
// 2023-03-09
import java.util.*;
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < nums1.length; i++){
for (int j = 0; j < nums2.length; j++){
if (nums1[i] == nums2[j] && !list.contains(nums2[j])){
list.add(nums2[j]);
}
}
}
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i++){
res[i] = list.get(i);
}
return res;
}
}
public class Test {
public static void main(String[] args) {
new Solution().intersection(new int[]{1,2,2,1}, new int[]{2, 2}); // 输出:[2]
new Solution().intersection(new int[]{4,9,5}, new int[]{9,4,9,8,4}); // 输出:[9,4]
}
}
【代码】admin
思路: 基于内部set取交集
package com.company;
// 2023-03-09
import java.util.*;
import java.util.stream.Collectors;
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = Arrays.stream(nums1).boxed().collect(Collectors.toSet());
Set<Integer> set2 = Arrays.stream(nums2).boxed().collect(Collectors.toSet());
set1.retainAll(set2);
int[] res = new int[set1.size()];
int index = 0;
for (Integer x : set1){
res[index] = x;
index++;
}
System.out.println(Arrays.toString(res));
return res;
}
}
public class Test {
public static void main(String[] args) {
new Solution().intersection(new int[]{1,2,2,1}, new int[]{2, 2}); // 输出:[2]
new Solution().intersection(new int[]{4,9,5}, new int[]{9,4,9,8,4}); // 输出:[9,4]
}
}
【代码】admin
思路: 把一个加入hash中然后判断
package com.company;标签:交集,res,nums1,int,LeeCode,new,intersection,349,nums2 From: https://blog.51cto.com/u_13682316/6111382
// 2023-03-09
import java.util.*;
import java.util.stream.Collectors;
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
List<Integer> list = Arrays.stream(nums2).boxed().collect(Collectors.toList());
List<Integer> res = new ArrayList<>();
for (int i = 0; i < nums1.length; i++){
if (list.contains(nums1[i]) && !res.contains(nums1[i])){
res.add(nums1[i]);
}
}
int[] re = new int[res.size()];
for (int i = 0; i < res.size(); i++){
re[i] = res.get(i);
}
return re;
}
}
public class Test {
public static void main(String[] args) {
new Solution().intersection(new int[]{1,2,2,1}, new int[]{2, 2}); // 输出:[2]
new Solution().intersection(new int[]{4,9,5}, new int[]{9,4,9,8,4}); // 输出:[9,4]
}
}