题目:
计算两个数组的交
样例
nums1 = [1, 2, 2, 1]
, nums2 = [2, 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> qq;
sort(nums1.begin(),nums1.end());
sort(nums2.begin(),nums2.end());
int i=0;
int j=0;
int n1=nums1.size();
int n2=nums2.size();
while(i<n1&&j<n2)
{
if(nums1[i]==nums2[j])
{
qq.push_back(nums1[i]);
i++;j++;
}
else if(nums1[i]<nums2[j])
{
i++;
}
else if(nums1[i]>nums2[j])
{
j++;
}
}
return qq;
}
};
感想:
基于上一个题的思路,这个题就直接去掉判断重复元素的语句即完成了题目的要求。排序,比较,脚标后移的方法的确比for循环好很多。