Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2]
Note:
- Each element in the result must be unique.
- The result can be in any order.
分析:
要找两个数组的交集,返回结果中元素不重复,无顺序。可以先对两个数组进行排序,分别用两个指针i、j遍历两个数组,若数组1元素大,则j++,若数组2元素大,则i++,若相等,若结果数组res为空或者未出现过当前元素,则将当前元素放入res中。
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
int len1 = nums1.size();
int len2 = nums2.size();
sort(nums1.begin() , nums1.end());
sort(nums2.begin() , nums2.end());
int i = 0;
int j = 0;
vector<int> res;
while(i<len1 && j<len2)
{
if(nums1[i] < nums2[j])
i++;
else if(nums1[i] > nums2[j])
j++;
else
{
if(res.empty() || res.back()!=nums1[i])
res.push_back(nums1[i]);
i++;
j++;
}
}
return res;
}
};