zoukankan      html  css  js  c++  java
  • LeetCode 350 Intersection of Two Arrays II

    Problem:

    Given two arrays, write a function to compute their intersection.

    Example:
    Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2, 2].

    • Each element in the result should appear as many times as it shows in both arrays.
    • The result can be in any order.

    Summary:

    求两集合交集,允许有重复元素出现。

    Analysis:

    1. sort + merge

        首先将两个数组从小到大排序,后分别用两个指针指向两个数组开头比较大小,将小的数组指针后移。直至两指针指向数字相等时考虑将数字放入res中。

      这道题不用考虑res中是否包含该数字。

     1 class Solution {
     2 public:
     3     vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
     4         vector<int> res;
     5         int len1 = nums1.size(), len2 = nums2.size();
     6         
     7         sort(nums1.begin(), nums1.end());
     8         sort(nums2.begin(), nums2.end());
     9         
    10         int i = 0, j = 0;
    11         while (i < len1 && j < len2) {
    12             if (nums1[i] < nums2[j]) {
    13                 i++;
    14             }
    15             else if (nums1[i] > nums2[j]) {
    16                 j++;
    17             }
    18             else {
    19                 res.push_back(nums1[i]);
    20                 i++;
    21                 j++;
    22             }
    23         }
    24         
    25         return res;
    26     }
    27 };

    2. Hash表建立数组中数字和出现次数的映射,再在第二个数组中进行查找,注意每找到一个,要在map中将该元素出现次数减1。

     1 class Solution {
     2 public:
     3     vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
     4         vector<int> res;
     5         map<int, int> m;
     6         int len1 = nums1.size(), len2 = nums2.size();
     7         
     8         for (int i = 0; i < len1; i++) {
     9             m[nums1[i]]++;
    10         }
    11         
    12         for (int i = 0; i < len2; i++) {
    13             if (m[nums2[i]]-- > 0) {
    14                 res.push_back(nums2[i]);
    15             }
    16         }
    17         
    18         return res;
    19     }
    20 };
  • 相关阅读:
    树莓派交叉编译环境搭建
    手机购买怎样识别假货——一点心得体会分享!
    Ubuntu 网站服务器环境搭建
    转载:Raspberry Pi 树莓派入门
    Python中的条件选择和循环语句
    关于VMare中安装Ubuntu的一些说明
    如何去掉系统快捷方式的箭头和更改登录界面背景图片
    重装系统后,硬盘分区丢失的解决办法
    Python中的字符串
    Python的基础语法
  • 原文地址:https://www.cnblogs.com/VickyWang/p/6012786.html
Copyright © 2011-2022 走看看