LeetCode 349. 两个数组的交集

349. 两个数组的交集

基本思路

set实现单个数组无重复数,set.contains()选取重复数,iterator().hasNext()迭代器遍历set读取结果。

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> set2 = new HashSet<>();
        for (int i=0; nums1 != null && i<nums1.length; i++){
            set1.add(nums1[i]);
        }
        for (int i=0; nums2 != null && i<nums2.length; i++){
            if(set1.contains(nums2[i])){
                set2.add(nums2[i]);
            }            
        }
        
        if (set2.isEmpty()) {
            return new int[0];
        }

        int[] res = new int[set2.size()];
        Iterator<Integer> iterator = set2.iterator();
        int idx = 0;
        while (iterator.hasNext()) {
            res[idx++] = iterator.next();
        }

        return res;
        
    }
}

改进

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        int max = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        
        for (int num1:nums1) { //找到nums1中最大最小值
            max = Math.max(num1, max);
            min = Math.min(num1, min);
        }
        
        boolean[] marks = new boolean[max-min+1];
        for (int num1:nums1) { //记录num1在marks中有的数
            marks[num1-min] = true;
        }
        
        int index = 0;
        for (int num2:nums2) {
            
            if (num2 < min || num2 > max) {//跳过num2中比num1中最大值大最小值小的数
                continue;
            }
            
            if (marks[num2-min]) {//用num1之前赋值好了增加的组进行判断,num2负责读取
                nums2[index++] = num2; // 合理使用 nums2 数组,将符合条件的数放到 nums2 的前面索引位置
                marks[num2-min] = false; // 设置 false,重复的数字就会被过滤掉
            }
        }
        
        return Arrays.copyOf(nums2, index); // 取 num2 数组从 0 开始 index 长度的子数组
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值