349. Intersection of Two Arrays
- Total Accepted: 33720
- Total Submissions: 75833
- Difficulty: Easy
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2]
.
Note:
- Each element in the result must be unique.
- The result can be in any order.
思路:求交集。
代码:
方法一:直接用unordered_set,复杂度比下面的方法低。
class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { unordered_set<int> m(nums1.begin(), nums1.end()); vector<int> res; for (int a:nums2) if (m.erase(a)) res.push_back(a); return res; } };
方法二:先排序,再遍历,nums1[i]==nums2[j]时插入新集合res,注意重复元素的情况。
1 class Solution { 2 public: 3 vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { 4 sort(nums1.begin(),nums1.end()); 5 sort(nums2.begin(),nums2.end()); 6 vector<int> res; 7 int i=0,j=0; 8 while(i<nums1.size()&&j<nums2.size()){ 9 while(i+1<nums1.size()&&nums1[i]==nums1[i+1]) i++;//去除重复元素 10 while(j+1<nums2.size()&&nums2[j]==nums2[j+1]) j++; 11 if(nums1[i]==nums2[j]){ 12 res.push_back(nums2[j]); 13 i++; 14 j++; 15 } 16 else{ 17 nums1[i]>nums2[j]?j++:i++; 18 } 19 /* 20 //else部分改成下面就是求并集 21 else{ 22 nums1[i]>nums2[j]?res.push_back(nums2[j++]):res.push_back(nums1[i++]); 23 } 24 */ 25 } 26 return res; 27 } 28 };
方法三:先排序,再用二分查找,注意二分查找的返回条件。
1 class Solution { 2 public: 3 vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { 4 vector<int> res; 5 if(!nums1.size()||!nums2.size()) return res; 6 sort(nums1.begin(),nums1.end()); 7 sort(nums2.begin(),nums2.end()); 8 for(int i=0;i<nums1.size();i++){ 9 while(i+1<nums1.size()&&nums1[i]==nums1[i+1]) i++; 10 if(BinarySearch(nums2,nums1[i])){ 11 res.push_back(nums1[i]); 12 } 13 } 14 return res; 15 } 16 bool BinarySearch(vector<int> nums2,int num){ 17 int left=0,right=nums2.size()-1,mid; 18 while(left<=right){ 19 mid=left+(right-left)/2; 20 if(nums2[mid]<num){ 21 left=mid+1; 22 } 23 else{ 24 right=mid-1; 25 } 26 } 27 return left<nums2.size()&&nums2[left]==num; 28 } 29 };