LeetCode350 Intersection of Two Arrays II

文章目录
  1. 1. 描述
  2. 2. 样例
  3. 3. 思路
  4. 4. 代码

描述

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

Note:

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

样例

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

思路

求两个数组的交,结果不去重。

具体解法可参考LeetCode349-Intersection-of-Two-Arrays这题,只不过少掉了去重操作而已。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
int n = nums1.size(), m = nums2.size(), i = 0, j = 0;
vector<int> ans;
while (i < n && j < m) {
if (nums1[i] < nums2[j]) i++;
else if (nums1[i] > nums2[j]) j++;
else {
ans.push_back(nums1[i]);
i++; j++;
}
}
return ans;
}
};
分享到 评论