原文题目:
349. Intersection of Two Arrays
读题:
该题用python来做的话将会很简单,具体可以参照另一篇博客python中求两个list的交集、并集、差集
而用C++的话想对绕一些,但也可以借助于STL中的set来做,集合做交集最适合了
python代码:
class Solution(object): def intersection(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ intersec = [item for item in nums1 if item in nums2] return list(set(intersec)) if __name__ == '__main__': l1 =[1,2,3,3,2,1] l2 =[3,2,5] temp = Solution() print(temp.intersection(l1,l2))
C++代码:
class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { set <int> s1; set <int> s2; vector <int> result; set <int>::iterator ite1; set <int>::iterator ite2; int i =0; int j = 0; for(;i<nums1.size();i++) { s1.insert(nums1[i]); } for(;j<nums2.size();j++) { s2.insert(nums2[j]); } ite1 = s1.begin(); ite2 = s2.begin(); while(ite1 != s1.end()&&ite2 != s2.end()) { if(*ite1 == *ite2) { result.push_back(*ite1); ite1++; ite2++; } else if(*ite1 < *ite2) { ite1++; } else { ite2++; } } return result; } }; int main() { Solution s; vector <int> vec1; vector <int> vec2; vector <int> temp; vec1.push_back(1); vec1.push_back(2); vec1.push_back(3); vec1.push_back(2); vec1.push_back(1); vec2.push_back(2); vec2.push_back(3); vec2.push_back(5); temp = s.intersection(vec1,vec2); for(int i =0; i < temp.size();i++) { cout << temp[i] << endl; } getchar(); }