Skip to content

Latest commit

 

History

History
executable file
·
52 lines (45 loc) · 2.86 KB

349. Intersection of Two Arrays.md

File metadata and controls

executable file
·
52 lines (45 loc) · 2.86 KB

#

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 ##(一)题目

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.

##(二)解题

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        vector<int> ret;
        if(nums1.empty()||nums2.empty()) return ret;
        sort(nums1.begin(),nums1.end());//首先对两个数组排序
        sort(nums2.begin(),nums2.end());
        auto iter1 = nums1.begin();
        auto iter2 = nums2.begin();
        auto end1 = nums1.end();
        auto end2 = nums2.end();
        while(iter1 != end1&&iter2!=end2)//其中一个遍历完就退出
        {
            if(*iter1<*iter2){//*iter2大就把iter1往后找
                ++iter1;
            }
            else if(*iter1>*iter2){//*iter1大就把iter2往后找
                ++iter2;
            }
            else {//找到了交集
                ret.push_back(*iter1);//存储交集
                ++iter1;
                ++iter2;
                while(iter1<end1&&*iter1==*(iter1-1)) ++iter1;//去除重复

                while(iter2<end2&&*iter2==*(iter2-1)) ++iter2;//同上
            }
        }
        return ret;
    }
};