LeetCode-350 Intersection of Two Arrays II
来源:互联网 发布:linux 统计大文件行数 编辑:程序博客网 时间:2024/05/16 10:38
https://leetcode.com/problems/intersection-of-two-arrays-ii/
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.
二者差别是此题不需要去重
1、调用set_intersection(12ms)
class Solution {
public:vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
vector<int> num(500);
sort(nums1.begin(),nums1.end());
sort(nums2.begin(),nums2.end());
auto iter = set_intersection(nums1.begin(),nums1.end(),nums2.begin(),nums2.end(),num.begin());
num.resize(iter-num.begin());
return num;
}
};
2、sort排序后,利用两个指针扫描(8ms)
class Solution {public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
vector<int> num;
sort(nums1.begin(),nums1.end());
sort(nums2.begin(),nums2.end());
int len1 = nums1.size(), len2 = nums2.size(), i = 0, j = 0;
while(i < len1 && j < len2){
if(nums1[i] == nums2[j]){
num.push_back(nums1[i]);
i++;
j++;
continue;
}
if(nums1[i] < nums2[j])
i++;
else
j++;
}
return num;
}
};
0 0
- LeetCode 350:Intersection of Two Arrays II
- LeetCode-350 Intersection of Two Arrays II
- leetcode-Intersection of Two Arrays II-350
- LeetCode 350 Intersection of Two Arrays II
- Leetcode-350-Intersection of Two Arrays II
- Leetcode 350 Intersection of Two Arrays II
- [leetcode][350] Intersection of Two Arrays II
- leetcode-350-Intersection of Two Arrays II
- LeetCode 350 Intersection of Two Arrays II
- leetcode 350 Intersection of two arrays II
- Leetcode 350 Intersection of Two Arrays II
- leetcode 350-Intersection of Two Arrays II
- leetcode note--leetcode 350 Intersection of Two Arrays II
- [LeetCode] Intersection of Two Arrays II
- LeetCode Intersection of Two Arrays II
- LeetCode 350. Intersection of Two Arrays II
- LeetCode:Intersection of Two Arrays II
- leetcode.350. Intersection of Two Arrays II
- 获取NVIDIA显卡的温度
- 面向对象
- thinkphp3.2【跨控制器调用】
- 基于UDP协议的网络程序
- tikz-函数计算pgfmathparse,pgfmathresult
- LeetCode-350 Intersection of Two Arrays II
- H.264+pcm(实时转aac) 封装mp4 iOS,android,Linux 写文件,效率高.iOS支持写1080P.
- Python包的编写和使用
- 深入理解HTTP Session
- vector
- Codeforces Round #357 (Div. 2)
- 用Java语言编写简单聊天程序
- PHP面向对象所学部分
- 【DRP分销】---java基础开发框架由来