[LeetCode] Intersection of Two Arrays 两个数组的交集
来源:互联网 发布:中日经济数据 编辑:程序博客网 时间:2024/06/05 04:31
声明:原题目转载自LeetCode,解答部分为原创
Problem :
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.
Solution:
思路:判断交集,先排序,再用两个指针分别从头到尾指向两个数组的元素。当两指针指向数值相同时,判断该数值是否存在sub容器中,方式是比较数值与sub容器的最后一位的数值是否相等,若不等,将数值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> intersection(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.intersection(text_1, text_2);output(sub);return 0;}
0 0
- [LeetCode] Intersection of Two Arrays 两个数组的交集
- Leetcode :Intersection of Two Arrays 两个数组的交集
- 349. Intersection of Two Arrays | 找两个数组的交集
- [LeetCode]349. Intersection of Two Arrays(两数组的交集)
- leetcode 349. Intersection of Two Arrays 数组的交集
- [easy]【leetcode】【java】 Intersection of Two Arrays II 两个数组的交集
- leetcode-350 Intersection of Two Arrays II 求两个数组的交集 面试见到了吗?
- [LeetCode] Intersection of Two Arrays II 两个数组的交集II
- leetcode 350. Intersection of Two Arrays II 两个数组的交集
- Leetcode:350. Intersection of Two Arrays II 求两个数组的交集
- 349. Intersection of Two Arrays 两个数组交集
- Intersection of Two Arrays II两个数组交集(重要!)
- [LeetCode]350. Intersection of Two Arrays II(求两个数组交集 II)
- LeetCode 349. Intersection of Two Arrays(数组交集)
- LeetCode 350. Intersection of Two Arrays II(数组交集)
- 349.leetcode Intersection of Two Arrays(easy)[数组 交集 set]
- Intersection of Two Arrays--求两个向量的交集
- (LeetCode)Intersection of Two Arrays --- 求交集
- 19. Remove Nth Node From End of List Medium
- DS.Lab筆記
- Linux命令大全(六)--Linux文件系统
- Android显示具体位置地图
- 数据的交换输出
- [LeetCode] Intersection of Two Arrays 两个数组的交集
- $.ajax()方法详解
- 1004. 成绩排名 (20)(Java实现)
- 操作符和表达式的总结
- kali Docker image
- java学习日志(八)-- 匿名对象、封装、构造函数
- 有return时try catch finally的执行顺序
- 图解正向代理、反向代理、透明代理
- javascript方法调用