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 };
posted @ 2016-10-30 11:49  SillyVicky  阅读(377)  评论(0编辑  收藏  举报