Intersection of Two Arrays
来源:互联网 发布:linux分頁地址 编辑:程序博客网 时间:2024/05/16 10:21
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.
Subscribe to see which companies asked this question.
根据问题分析,本题的目的是为了寻求两个数组的交集,以类作为实现。
我们首先创建一个函数:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2)
其中nums1是第一个vector,nums2是第二个vector。下面我们将这个函数完善。
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
int temp;
vector<int> nums3;
int size = nums3.size();
for(int i = 0; i < nums1.size(); i ++) {
for(int j = 0; j < nums2.size(); j ++) {
bool index = 0;
if(nums1[i] == nums2[j]) {
for(int k = 0; k < size; k++){
if(nums3[k] == nums2[j])
index = 1;
}
if(! index){
nums3.push_back(nums2[j]);
size ++;
}
}
}
}
return nums3;
}
下面编写mian函数,进行测试
int main() {
vector<int> nums1,nums2;
nums1.push_back(1);
nums1.push_back(2);
nums1.push_back(2);
nums1.push_back(1);
nums2.push_back(2);
nums2.push_back(1);
int n = intersection(nums1,nums2).size();
cout << "[";
for(int l = 0;l < n - 1; l ++){
cout<< intersection(nums1, nums2)[l] << ",";
}
cout << intersection(nums1,nums2)[n-1] << "]" <<endl;
return 0;
}
输出结果为[1,2],即测试通过。
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of two arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Intersection of Two Arrays
- Elasticsearch(十二)【NEST高级客户端--规范】
- macOS系统安装eclipse svn插件及问题解决
- 解决运行ASP.NET MVC项目时,因版本不一致导致无法运行的问题
- android studio 官网下载+安装(win7)
- HDU--2191(多重背包)
- Intersection of Two Arrays
- 129. Sum Root to Leaf Numbers
- [编程之美-11]字符串的全排列问题
- HBCTF——WriteUp&&涨姿势(3)
- 08---进程控制
- Share a peice of movie script from Rocky Ⅵ which I love the most.
- FragmentPagerAdapter
- bn 层及其变种
- JSP总结