随笔 - 455  文章 - 9  评论 - 17  阅读 - 18万

leetcode 350. Intersection of Two Arrays II

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?

求两个数组的交集。

class Solution {
public:
    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
        vector<int> v;
        unordered_map<int, int> mp;
        for (int i = 0 ; i < nums1.size(); ++i) {
            mp[nums1[i]] += 1;
        }
        int n = nums1.size();
        for (int i = 0; i < nums2.size(); ++i) {
            if (mp[nums2[i]]) {
                mp[nums2[i]]--;
                v.push_back(nums2[i]);
            }
        }
        return v;
    }
};
posted on   Beserious  阅读(96)  评论(0编辑  收藏  举报
编辑推荐:
· MySQL 优化利器 SHOW PROFILE 的实现原理
· 在.NET Core中使用异步多线程高效率的处理大量数据
· 聊一聊 C#前台线程 如何阻塞程序退出
· 几种数据库优化技巧
· 聊一聊坑人的 C# MySql.Data SDK
阅读排行:
· 为什么推荐在 .NET 中使用 YAML 配置文件
· 在 .NET Core 中使用 Channel 实现生产者消费者模式
· 干掉EasyExcel!FastExcel初体验
· .NET 阻止系统睡眠/息屏
· .NET 9 中的 多级缓存 HybridCache
< 2024年12月 >
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 1 2 3 4
5 6 7 8 9 10 11

点击右上角即可分享
微信分享提示