LeetCode 350 Intersection of Two Arrays II

Posted SillyVicky

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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> intersection(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                 if (res.empty() || res.back() != nums1[i]) {
20                     res.push_back(nums1[i]);
21                 }
22                 
23                 i++;
24                 j++;
25             }
26         }
27         
28         return res;
29     }
30 };

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 };

以上是关于LeetCode 350 Intersection of Two Arrays II的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 350. Intersection of Two Arrays II

LeetCode(350)Intersection of Two Arrays II

LeetCode 350 Intersection of Two Arrays II

350. Intersection of Two Arrays II(LeetCode)

LeetCode 350. Intersection of Two Arrays II

Leetcode 350. Intersection of Two Arrays II