leetcode上第350号问题:Intersection of Two Arrays II
给定两个数组,编写一个函数来计算它们的交集。 示例 1: 输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2,2] 示例 2: 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 输出: [4,9] 说明:
容器类map的使用。
1// 350. Intersection of Two Arrays II
2// https://leetcode.com/problems/intersection-of-two-arrays-ii/description/
3// 时间复杂度: O(nlogn)
4// 空间复杂度: O(n)
5class Solution {
6public:
7 vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
8
9 map<int, int> record;
10 for(int i = 0 ; i < nums1.size() ; i ++){
11 record[nums1[i]] += 1;
12 }
13
14 vector<int> resultVector;
15 for(int i = 0 ; i < nums2.size() ; i ++){
16 if(record[nums2[i]] > 0){
17 resultVector.push_back(nums2[i]);
18 record[nums2[i]] --;
19 }
20 }
21
22 return resultVector;
23 }
24};