标签:public nbsp 技术分享 cti ack else amp poi pac
[349] Intersection of Two Arrays [Easy]
两个无序可重复数组找交集, 交集要求元素唯一。
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2]
.
思路:1、两个unordered_set 可以去重; 2、先排序,双指针
1 //Space:O(N); Time: 0(N) 2 //unordered_set insert, emplace, find, delete O(1) 3 4 class Solution { 5 public: 6 vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { 7 unordered_set<int> st1; 8 for (auto ele: nums1) { 9 st1.emplace(ele); 10 } 11 unordered_set<int> st2; 12 for (auto ele: nums2) { 13 if (st1.find(ele) != st1.end()) { 14 st2.emplace(ele); 15 } 16 } 17 vector<int> ans; 18 for (auto ele: st2) { 19 ans.push_back(ele); 20 } 21 return ans; 22 } 23 };
1 //space: no extra sapce, time(nlog(n)) 2 //two pointers 3 class Solution { 4 public: 5 vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { 6 sort(nums1.begin(), nums1.end()); 7 sort(nums2.begin(), nums2.end()); 8 vector<int>::size_type idx1 = 0, idx2 = 0; 9 vector<int> ans; 10 while(idx1 < nums1.size() && idx2 < nums2.size()) { 11 if(nums1[idx1] == nums2[idx2]) { 12 if (ans.empty() || nums1[idx1] != ans.back()) { //使用api之前一定先做条件检测 13 ans.push_back(nums1[idx1]); 14 } 15 idx1++, idx2++; 16 } else if (nums1[idx1] < nums2[idx2]) { 17 ++idx1; 18 } else { 19 ++idx2; 20 } 21 } 22 return ans; 23 } 24 };
标签:public nbsp 技术分享 cti ack else amp poi pac
原文地址:http://www.cnblogs.com/zhangwanying/p/6661503.html