LeetCode: Intersection of Two Arrays

来源:互联网 发布:java 启动main 编辑:程序博客网 时间:2024/05/18 03:05

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 orde
给定两个数组,找出两个数组中重合的元素,返回结果中元素不得重复。

使用set代码

class Solution {public:    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {     set<int> s1;     set<int> s2;          int n1 = nums1.size();     int n2 = nums2.size();     for (int i = 0; i < n1; ++i) s1.insert(nums1[i]);     for (int i = 0; i < n2; ++i) s2.insert(nums2[i]);     vector<int> res;     set<int>::iterator it1 = s1.begin();     set<int>::iterator it2 = s2.begin();          while(it1 != s1.end() && it2 != s2.end())     {         if (*it1 == *it2) {             res.push_back(*it1);             it1++;             it2++;         }         else if (*it1 < *it2) it1++;         else it2++;     }        return res;    }    };


1 0
原创粉丝点击