350. Intersection of Two Arrays II寻找两个数组交集Java

给定两个整数数组nums1and nums2,返回它们的交集数组。结果中的每个元素必须出现与它在两个数组中显示的一样多的次数,并且您可以按任何顺序返回结果。

示例 1:
输入: nums1 = [1,2,2,1],nums2 = [2,2]
输出: [2,2]

示例 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [4,9]
解释: [9,4] 也被接受。

约束:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000

方法1Map

  1. 建立一个用其中一个数组建立一个map, 遍历另一个数组的数是否存在map中, 存在则存入需要输出的结果数组中并将对应数的value-1
  2. 为了节省空间, 用较小的数组建立map
  3. 将key对应的value值-1: map.values().removeIf(f -> f == 0);
  4. 将结果List输出为int[]: res.stream().mapToInt(i->i).toArray();
class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        int l1 = nums1.length, l2 = nums2.length;
        int[] temp = new int[]{};
        int[] temp2 = new int[]{};
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        if (l1 < l2) {
            temp = nums1;
            temp2 = nums2;
        } else {
            temp = nums2;
            temp2 = nums1;
        }
        for (int i : temp) {
            if (map.containsKey(i)) {
                map.put(i, map.get(i) + 1);
            }else{
                map.put(i, 1);
            }
        }
        List<Integer> res =new ArrayList<Integer>();
        for (int i=0;i< temp2.length;i++) {
            if (!map.containsKey(temp2[i])) {
                continue;
            } else {
                res.add(temp2[i]);
                map.put(temp2[i], map.get(temp2[i]) - 1);
                map.values().removeIf(f -> f == 0);
            }
        }
        return res.stream().mapToInt(i->i).toArray();
    } 
}

时间复杂度O(n+m)
但是leetcode运行了15ms看起来比较慢, 所以有了下面的想法

方法2指针

  1. 将两个数组排序, 然后遍历两个数组, 当都存在时存到结果List中
  2. 定义两个指针分别指向排序后的数组的第一个数
  3. 都存在则res.add()
  4. 不存在则指针向后挪一位
  5. 当两个指针其中的一个值等于该数组长度时遍历结束
  6. 返回res.stream().mapToInt(Integer::intValue).toArray();
class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int i=0, j=0;
        List<Integer> res = new ArrayList<>();
        while(i<nums1.length && j<nums2.length) {
            if(nums1[i] == nums2[j]) {
                res.add(nums1[i]);
                i++;
                j++;
            }  else if (nums1[i] < nums2[j]) {
                i++;
            } else {
                j++;
            }
        }
        return res.stream().mapToInt(Integer::intValue).toArray();
    }   
}

时间复杂度O(min(n,m))
leetcode运行了5ms

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值