Leetcode 350. 两个数组的交集 II (简单题有大学问)

这个题目的第一种思路就是:用一个哈西表来存储nums1的里面的元素出现的个数(或者存储nums2的也行),然后遍历一遍nums2的元素,判断是否将元素加入答案中!!!

Python:

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        cnt = defaultdict(int)
        ans = []
        for x in nums1:
            cnt[x] += 1
        for x in nums2:
            if (cnt[x] != 0):
                ans.append(x)
                cnt[x] -= 1
        return ans

C++:

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        unordered_map<int, int> cnt;
        for (auto x: nums1) {
            cnt[x] ++;
        }
        vector<int> ans;
        for (auto x: nums2) {
            if (cnt[x] != 0) {
                ans.push_back(x);
                cnt[x] --;
            }
        }
        return ans;
    }
};

进阶一:

        如果数组已经排好序了,那么可以采用双指针的思路。定义两个指针分别指向nums1, nums2的头部,然后逐一遍历,如果nums1[id1] > nums2[id2],那么就 id2++,如果nums1[id1] > nums2[id2],则 id1 ++,如果相等的话,那么就将指针都往后移动一位,且这个元素为交集,并且将元素加入答案中。

Python:

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        nums1.sort()
        nums2.sort()
        n, m = len(nums1), len(nums2)
        id1, id2 = 0, 0
        ans = []
        while id1 < n and id2 < m:
            if nums1[id1] > nums2[id2]:
                id2 += 1
            elif nums1[id1] < nums2[id2]:
                id1 += 1
            else:
                ans.append(nums1[id1])
                id1 += 1
                id2 += 1
        return ans

C++:

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        int id1 = 0, id2 = 0;
        int n = nums1.size(), m = nums2.size();
        sort(nums1.begin(), nums1.end());
        sort(nums2.begin(), nums2.end());
        vector<int> ans;
        while (id1 < n && id2 < m) {
            if (nums1[id1] > nums2[id2]) {
                id2 ++;
            }
            else if (nums1[id1] < nums2[id2]) {
                id1 ++;
            }
            else {
                ans.emplace_back(nums1[id1]);
                id1 ++;
                id2 ++;
            }
        }
        return ans;
    }
};

进阶二:

        如果排好序,则使用方法二!!!!!

进阶三:

        如果如果 nums 2的元素存储在磁盘上,磁盘内存是有限的,并且你不能一次加载所有的元素到内存中。那么就无法高效地对 nums2进行排序,因此推荐使用方法一而不是方法二。在方法一中,nums2​只关系到查询操作,因此每次读取 nums2中的一部分数据,并进行处理即可。(进阶三是参考答案滴!!因为觉得自己讲不清楚~~~~)

持续学习,加油!!!!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值