[LeetCode] Intersection of Two Arrays II 两个数组的交集II
声明:原题目转载自LeetCode,解答部分为原创
Problem :
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2,
2]
, return [2, 2]
.
Note:
- Each element in the result should appear as many times as it shows in both arrays.
- The result can be in any order.
思路:判断交集,先排序,再用两个指针分别从头到尾指向两个数组的元素。与上一题不同的是,当两指针指向数值相同时,直接将数值push进sub容器, 并将两个指针指向下一位;当数值不等时,数值小的一方将指针指向下一位。重复以上操作直至其中一方数值比较完。
代码如下:
#include<iostream> #include<vector> #include<algorithm> using namespace std; void output(vector<int> & temp) { for(int i = 0 ; i < temp.size() ; i ++) { cout << temp[i] << " "; } cout << endl; } class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); vector<int> sub; int point_1 = 0; int point_2 = 0; while(point_1 < nums1.size() && point_2 < nums2.size()) { if(nums1[point_1] == nums2[point_2]) { if(!sub.empty()) { int pre_size = sub.size(); int sub_num = sub[pre_size - 1]; if(sub_num != nums1[point_1]) sub.push_back(nums1[point_1]); } else sub.push_back(nums1[point_1]); point_1 ++; point_2 ++; continue; } else if(nums1[point_1] < nums2[point_2]) { point_1 ++; continue; } else { point_2 ++; continue; } } return sub; } }; int main() { vector<int> text_1; vector<int> text_2; vector<int> sub; text_1.push_back(1); text_1.push_back(2); text_2.push_back(2); text_2.push_back(1); Solution text; sub = text.intersect(text_1, text_2); output(sub); return 0; }
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇:没有了
- 下一篇:没有了