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

LeetCode

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

LeetCode

题目链接
  • https://leetcode.cn/problems/intersection-of-two-arrays-ii/
解题思路
  • 使用哈希表存储每个数字出现的次数,为了方便,我们先确定短数组
  • 遍历短数组,并在哈希表中记录其每个数字和对应出现的次数
  • 然后遍历长数组,对于长数组中的每个数字,如果在哈希表中存在这个数字,则将这个数字添加到答案中,并将对应出现次数减一
AC代码
class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        if (nums1.length > nums2.length) {
            return intersect(nums2, nums1);
        }
        Map map1 = new HashMap<>();
        for (int i : nums1) {
            int count = map1.getOrDefault(i, 0) + 1;
            map1.put(i, count);
        }
        int[] ans = new int[nums1.length];
        int index = 0;
        for (int i : nums2) {
            int count = map1.getOrDefault(i, 0);
            if (count > 0) {
                ans[index++] = i;
                count--;
                if (count > 0) {
                    map1.put(i, count);
                } else {
                    map1.remove(i);
                }
            }
        }
        return Arrays.copyOfRange(ans, 0, index);
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1006291.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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