Intersection of Two Arrays II
2016-07-08 09:31
447 查看
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 =
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to num2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
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.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to num2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
#include<iostream> #include<set> #include<vector> #include<map> #include<algorithm> using namespace std; vector<int> intersection(vector<int>a, vector<int>b); int main() { vector<int>a = { 1, 2,2, 1 }; vector<int>b = { 2, 2,1 }; vector<int>temp; temp = intersection(a, b); for (int d : temp) cout << d << endl; system("pause"); return 0; } vector<int> intersection(vector<int>a, vector<int>b) { vector<int>temp; //map<int, int> m; //for (auto data : a) // m[data]++; //// map常用于统计数组中一个数的个数 //for (auto data : b) //{ // if (m[data] > 0) // { // temp.push_back(data); // m[data]--; // } //} sort(a.begin(), a.end()); sort(b.begin(), b.end()); int i = 0, j = 0; //不排序的话 不能判断重复数字 while (i < a.size() && j < b.size()) { if (a[i] == b[j]) { temp.push_back(a[i]); i++; j++; } else { if (a[i]>b[j]) { j++; } else { i++; } } } return temp; }
相关文章推荐
- 关于float的感悟
- maven pom.lastupdated
- Swift-基础语法之变量&常量&元组
- CSS中交集选择器详解
- CentOS 部署 Java Web
- 在图片上实现定位
- 【bzoj1316】【树上的询问】【点分治+map】
- Linux上使用Qt Creator进行C/C++开发
- linux守护进程
- 详解iOS App开发中Cookie的管理方法
- 微信公众平台开发——腾讯地图导航
- C/C++中static关键字作用总结
- Android模块化编程——炫酷小巧多功能Button
- 轮播图
- exec函数族
- Oracle修改已有数据的字段类型
- chrome浏览器的二维码插件
- 哈希表的知识点介绍
- ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统之前端页面框架构建源码分享
- sysconf()、pathconf()和fpathconf()函数