一.题目描述
返回两个数组的交
注意事项
- Each element in the result must be unique.
- The result can be in any order.
样例
nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, 返回 [2]
二.解题思路
返回两个数组的交
注意事项
- Each element in the result must be unique.
- The result can be in any order.
nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, 返回 [2]
先将两个数组的元素进行升序排列,用去重函数分别除掉数组中的相邻重复元素,再将两个数组进行比较,把两个数组中的相同元素放在一个新的向量中.
三.实现代码class Solution {
public:
/**
* @param nums1 an integer array
* @param nums2 an integer array
* @return an integer array
*/
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
// Write your code here
vector<int> nums3;
sort(nums1.begin(),nums1.end());
sort(nums2.begin(),nums2.end());
nums1.erase(unique(nums1.begin(),nums1.end()),nums1.end());
nums2.erase(unique(nums2.begin(),nums2.end()),nums2.end());
int i=0;
int j=0;
while(i<nums1.size()&&j<nums2.size()){
if(nums1[i]==nums2[j]){
nums3.push_back(nums1[i]);
i++;
j++;
}
if(nums1[i]<nums2[j]) i++;
if(nums1[i]>nums2[j]) j++;
}
return nums3;
}
};
一开始我用了双重循环将两个数组中的相同元素找出来放在一个新的向量中,再用去重函数对新向量去重,但结果一直wrong answer.改进的方法是先将两个数组排序,再用去重函数将相邻重复元素除掉,因为数组有序,所以找两个数组相同元素时只需要比较就可以,提高了效率.