leetcode 350. Intersection of Two Arrays II
时间:2019-09-17
本文章向大家介绍leetcode 350. Intersection of Two Arrays II,主要包括leetcode 350. Intersection of Two Arrays II使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
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 nums2'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?
1 // class Solution { 2 // public: 3 // vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { 4 // unordered_map<int, int> ctr; 5 // vector<int> res; 6 // for (auto i : nums1) ctr[i]++; 7 // for (auto i : nums2) { 8 // if (ctr.count(i) > 0 && ctr[i] > 0) { 9 // ctr[i]--; 10 // res.push_back(i); 11 // } 12 // } 13 // return res; 14 // } 15 // }; 16 17 class Solution { 18 public: 19 vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { 20 vector<int> res; 21 22 sort(nums1.begin(), nums1.end()); 23 sort(nums2.begin(), nums2.end()); 24 25 int i1 = 0, i2 = 0; 26 while(i1<nums1.size() && i2<nums2.size()){ 27 if(nums1[i1] == nums2[i2]){ 28 res.push_back(nums1[i1]); 29 i1++; 30 i2++; 31 } 32 else if(nums1[i1] < nums2[i2]){ 33 i1++; 34 } 35 else{ 36 i2++; 37 } 38 } 39 40 return res; 41 } 42 };
原文地址:https://www.cnblogs.com/qinduanyinghua/p/11531836.html
- Android i2c-tools移植
- 高通GPIO驱动(DTS方式)
- Dos烧录脚本
- 使用ServiceStack构建Web服务
- 《Redis设计与实现》读书笔记(二十三) ——Redis服务器初始化
- 警惕:Oracle中删除的分区不会进入回收站(Recyclebin)
- 《Redis设计与实现》读书笔记(二十五) ——Redis主从复制具体过程
- 基于input子系统的sensor驱动调试(一)
- 《Redis设计与实现》读书笔记(二十六) ——Redis哨兵(sentinel)启动与建立监听机制
- 《Redis设计与实现》读书笔记(二十七) ——Redis哨兵(sentinel)主服务器下线判断与故障转移
- 基于input子系统的sensor驱动调试(二)
- 编程语言中的闭包
- 《Redis设计与实现》读书笔记(二十八) ——Redis集群节点结构与槽分配
- Linux RCU 机制详解
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法