leetcode 350. Intersection of Two Arrays II

原创 2017年01月03日 09:02:31

https://leetcode.com/problems/intersection-of-two-arrays-ii/

妈蛋,我还是个弱鸡,这样的题目也不能解决,~~(>_<)~~,算了自己不正确的思路,就不写了
既然他们是有序的,当然在此之前是给她排序哈.

sort(nums1.begin(),nums1.end());
sort(nums1.begin(),nums1.end());

然后确定长度,这个我还是知道的,然后比较大小,进行扫描就好

int l1= (int)nums1.size();
int l2= (int)nums2.size();
int i1=0; int i2=0;
vector res<int>
while(i1<l1&&i2<l2)
{
if(nums1[i1]==nums2[i2]){
     res.push_back(nums1[i1]);
    i1++;
    i2++;
}
else if(nums1[i1]>nums2[i2]){
    i2++;
}
else{
i1++;
}
}
return res;

最后附上完整代码:

class Solution
publicvector <int> intersect(vector<int>& nums1, vector<int>& nums2) 
{
sort(nums1.begin(),nums2.end());
sort(nums2.begin(),nums2.end());
int l1=(int) size(nums1); int l2 =(int) size(nums2);

int i1=0;int i2=0;
vector <int> res;
while<i1<l1&&i2<l2)
{
if(nums1[i1]==nums2[i2]){

 res.push_back(nums[i1]);
 i1++;
 i2++;
 }
else if(nums1[i1]>nums2[i2]){
++i2;
}
else
++i1;
}
return res;
}

算法的时间:O(max(m,n))long(max(m,n)
space: O(m+n)

版权声明:本文为博主原创文章,未经博主允许不得转载。

leetcode350~Intersection of Two Arrays II

Given two arrays, write a function to compute their intersection. Example: Given nums1 = [1, 2, 2...

【Leetcode】350. Intersection of Two Arrays II

方法一: 思路: 用flag标记是否nums2中的该元素已经是相交的元素,若不是才加入结果list,并置flag为1然后跳出内层循环继续判断nums1的下一个元素。 public class Solu...

<LeetCode OJ> 349 / 350 Intersection of Two Arrays(I / II)

Total Accepted: 3212 Total Submissions: 6814 Difficulty: Easy Given two arrays, write a functio...

[leetcode] 350. Intersection of Two Arrays II

Given two arrays, write a function to compute their intersection. Example: Given nums1 = [1, 2, ...

[LeetCode] 350. Intersection of Two Arrays II

[LeetCode] 350. Intersection of Two Arrays II 解题思路
  • zhao_tw
  • zhao_tw
  • 2016年10月20日 19:52
  • 101

Leetcode——350. Intersection of Two Arrays II

题目Given two arrays, write a function to compute their intersection.Example: Given nums1 = [1, 2, 2,...

350. Intersection of Two Arrays II

Given two arrays, write a function to compute their intersection. Example: Given nums1 = [1, 2, 2, ...

leetcode解题之349 & 350. Intersection of Two Arrays Java版(求数组交集))

350. Intersection of Two Arrays II leetcode解题之349. Intersection of Two Arrays & 350. Intersection ...

350.[LeetCode]Intersection of Two Arrays

算法效率分析如下:// m n // 如果我用二分排序,那么时间就是 (nlogn + mlogm + m + n) // 但是用java的哈希表的话,时间可以缩短到 O(m+n),因为哈希表的插入时...

LeetCode-349&350.Intersection of Two Arrays

https://leetcode.com/problems/intersection-of-two-arrays/ Given two arrays, write a function to co...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode 350. Intersection of Two Arrays II
举报原因:
原因补充:

(最多只允许输入30个字)