栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 map = new HashMap();
        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 res =new ArrayList();
        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 res = new ArrayList<>();
        while(i 

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/424369.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号