前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode笔记:350. Intersection of Two Arrays II

LeetCode笔记:350. Intersection of Two Arrays II

作者头像
Cloudox
发布2021-11-23 15:34:45
2830
发布2021-11-23 15:34:45
举报
文章被收录于专栏:月亮与二进制月亮与二进制

问题:

Given two arrays, write a function to compute their intersection. Example: Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. Note: Each element in the result should appear as many times as it shows in both arrays. The result can be in any order. Follow up: What if the given array is already sorted? How would you optimize your algorithm? What if nums1's size is small compared to nums2's size? Which algorithm is better? What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

大意:

给出两个数组,写一个函数来计算他们的交叉点。 例子: 给出数组 nums1 = [1,2,2,1],nums2 = [2,2],返回[2,2]。 注意: 在结果中每个元素出现的次数应该与他们在两个数组中出现的次数一样。 结果可以是乱序的。 进阶: 如果给出的数组已经是排好序的呢?你会如何优化你的算法? 如果nums1的尺寸比nums2要小呢?哪个算法更好? 如果nums2中的元素是存储在硬盘上的,而由于内存是有限的你不能一次把所有元素都加载到内存中,怎么办?

思路:

这个问题是之前一个问题的简单变形:传送门:LeetCode笔记:349. Intersection of Two Arrays。这个题目的变化在于他不要求每个数字只出现一次了,而是要求交叉了几次就保留几次,这其实更简单,还是之前题目的解法,把保障数字唯一性的代码去掉就好了,速度依然很快,3ms。 对于它提出来的三个问题,解答如下:

  • 如果数组已经排好序了,更简单,把排序过程都省掉。
  • 如果nums1尺寸更小,这其实对于我的解法不影响,反正哪个数组先遍历完都会结束循环。
  • 如果nums2的元素不能一次读取,那就一个个读取然后在nums1中寻找相同的数字,只是如果找到了记得要在nums1中去掉该位置的数字,等把nums2比较完了或者nums1被减没了就结束了。

代码(Java):

代码语言:javascript
复制
public class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        int results[] = new int[nums1.length];// 结果数组
        
        // 没有数字的情况
        if (nums1.length == 0 || nums2.length == 0) {
            return new int[0];
        }
        
        // 先对两个数组排序
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        
        int index = 0;
        for (int i = 0, j = 0; i < nums1.length; ) {
            if (nums1[i] < nums2[j]) {// 第一个数组中数字小
                i++;
            } else if (nums1[i] == nums2[j]) {// 数字相同,放入结果数组
                results[index] = nums1[i];
                index++;
                i++;
                // 判断第二个数组有没有到最后一个数组,还没到才继续往后移去比
                if (j < nums2.length-1) j++;
                else break;
            } else {// 第二个数组中数字小,注意要判断是否到达最后一个数字
                if (j < nums2.length-1) j++;
                else break;
            }
        }
        
        return Arrays.copyOfRange(results, 0, index);// 结果数组只返回有数字的那一部分
    }
}

合集:https://github.com/Cloudox/LeetCode-Record

查看作者首页

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017/11/21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题:
  • 大意:
  • 思路:
  • 代码(Java):
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档