博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode 350. Intersection of Two Arrays II
阅读量:4491 次
发布时间:2019-06-08

本文共 1626 字,大约阅读时间需要 5 分钟。

350. Intersection of Two Arrays II

  • Total Accepted: 23510
  • Total Submissions: 56283
  • Difficulty: Easy

 

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.

 

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
intersect(vector
& nums1, vector
& nums2) { 4 unordered_map
m; 5 vector
res; 6 for(int i:nums1) m[i]++; 7 for(int i:nums2){ 8 if(m[i]-->0){ 9 res.push_back(i);10 }11 }12 return res;13 }14 };

 

 

方法二:

1 class Solution { 2 public: 3     vector
intersect(vector
& nums1, vector
& nums2) { 4 sort(nums1.begin(),nums1.end()); 5 sort(nums2.begin(),nums2.end()); 6 vector
res; 7 int i=0,j=0; 8 while(i
nums2[j]?j++:i++;18 }19 }20 return res;21 }22 };

 

转载于:https://www.cnblogs.com/Deribs4/p/5728223.html

你可能感兴趣的文章
[leetcode] Minimum Path Sum
查看>>
PAT乙级1021.个位数统计(15 分)
查看>>
强化学习Q-Learning算法详解
查看>>
Spring MVC
查看>>
winform treeview 复选框,父节点子节点联动Bug
查看>>
C#_委托类型以及Action/Fanc_2018Oct
查看>>
es数组去重的简写
查看>>
Training Logisches Denken
查看>>
谁分配谁释放
查看>>
正则表达式
查看>>
Java集合之LinkedHashSet源码分析
查看>>
David Silver强化学习Lecture1:强化学习简介
查看>>
开源项目
查看>>
mvc4 找到多个与名为“xx”的控制器匹配的类型
查看>>
unix系统内核优点
查看>>
协议(五)-从电报机到智能手机
查看>>
Solr学习
查看>>
HDU-4628 Pieces 搜索 | DP
查看>>
动态代理
查看>>
C++ 错误积累
查看>>