原题链接在这里: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.

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?

题解:

可以使用双指针.

Time Complexity: O(nlogn). Space: O(1).

AC Java:

 public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0;
int j = 0;
List<Integer> res = new ArrayList<Integer>();
while(i<nums1.length && j<nums2.length){
if(nums1[i] < nums2[j]){
i++;
}else if(nums1[i] > nums2[j]){
j++;
}else{
res.add(nums1[i]);
i++;
j++;
}
} int [] resArr = new int[res.size()];
int k = 0;
for(int num : res){
resArr[k++] = num;
}
return resArr;
}
}

Could use HashMap as well.

Time Complexity: O(m + n).

Space: O(Math.min(m, n)).

AC Java:

 class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
if(nums1 == null || nums2 == null){
return new int[0];
} HashMap<Integer, Integer> hm = new HashMap<>();
for(int num : nums1){
hm.put(num, hm.getOrDefault(num, 0) + 1);
} List<Integer> res = new ArrayList<>();
for(int num : nums2){
if(hm.containsKey(num)){
res.add(num);
if(hm.get(num) == 1){
hm.remove(num);
}else{
hm.put(num, hm.get(num) - 1);
}
}
} int [] resArr = new int[res.size()];
int i = 0;
for(int num : res){
resArr[i++] = num;
} return resArr;
}
}

Follow up 2 nums1 length is smaller. 用双指针先sort两个array明显没有利用到num1.length小的特性. 若是用HashMap来记录num1每个element出现频率再iterate nums2, 那么Time Complexity: O(m + n), m = nums1.length, n = num2.length. Space: O(m).

或者sort nums1 再对每一个num2的element在 sorted nums1上做 binary search. Time Complexity: O(mlogm + nlogm). Space: O(1).

由此可见,当m很小时,用HashMap和binary search就是time和space的trade off.

Follow up 3 nums2 is sorted but too big for memory. I/O的操作很贵,所以首先想到的是避免I/O的次数。

若是nums1可以全部load到memory上, 先sort nums1再把nums2从小到大分开load到memory来.

  if load进来这一段最大值, 也就是最后一个值<nums1[0] 或者 load进来这一段最小值, 也就是第一个值>nums1[nums1.length-1]可以直接跳过, load下一段.   else load进来这一段 和 sorted nums1做双指针.

若是nums1也太大了,就先external sort nums1, 在分开load进来nums1一段和nums2一段做双指针.

类似Find Common CharactersIntersection of Two Arrays.

LeetCode Intersection of Two Arrays II的更多相关文章

  1. [LeetCode] Intersection of Two Arrays II 两个数组相交之二

    Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, 2, 1] ...

  2. [LeetCode] 349 Intersection of Two Arrays && 350 Intersection of Two Arrays II

    这两道题都是求两个数组之间的重复元素,因此把它们放在一起. 原题地址: 349 Intersection of Two Arrays :https://leetcode.com/problems/in ...

  3. 26. leetcode 350. Intersection of Two Arrays II

    350. Intersection of Two Arrays II Given two arrays, write a function to compute their intersection. ...

  4. LeetCode Javascript实现 169. Majority Element 217. Contains Duplicate(两个对象比较是否相等时,如果都指向同一个对象,a==b才是true)350. Intersection of Two Arrays II

    169. Majority Element /** * @param {number[]} nums * @return {number} */ var majorityElement = funct ...

  5. 【leetcode】350. Intersection of Two Arrays II

    problem 350. Intersection of Two Arrays II 不是特别明白这道题的意思,例子不够说明问题: 是按顺序把相同的元素保存下来,还是排序,但是第二个例子没有重复... ...

  6. [LeetCode] Intersection of Two Arrays 两个数组相交

    Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, 2, 1] ...

  7. LeetCode Intersection of Two Arrays

    原题链接在这里:https://leetcode.com/problems/intersection-of-two-arrays/ 题目: Given two arrays, write a func ...

  8. [LintCode] Intersection of Two Arrays II 两个数组相交之二

    Given two arrays, write a function to compute their intersection.Notice Each element in the result s ...

  9. LeetCode_350. Intersection of Two Arrays II

    350. Intersection of Two Arrays II Easy Given two arrays, write a function to compute their intersec ...

随机推荐

  1. Power BI for Office 365(六)Power Map简介

    如果说Power BI中最给力的功能是什么,我觉得是Power Map.Power Map第一次是出现在SQL Server 2014的新特性里被提及,前身就是GeoFlow.在Power Map下可 ...

  2. js添加var和不加var区别

    var 声明的变量,作用域是当前 function 没有声明的变量,直接赋值的话, 会自动创建变量 但作用域是全局的. //----------------- function doSth() { a ...

  3. Python爬虫学习(5): 简单的爬取

    学习了urllib,urlib2以及正则表达式之后就可以做一些简单的抓取以及处理工作.为了抓取方便,这里选择糗事百科的网页作为抓取对象. 1. 获取数据: In [293]: url = " ...

  4. Ubuntu 用vsftpd 配置FTP服务器

    网上的文章好难懂啊..只想要简单粗暴,弄好能用就行啊,复杂的以后研究不行吗...折腾好久,其实弄出来能用不就这么点内容吗... 本文在Ubuntu Server 14.04 amd64系统测试. Ma ...

  5. PHP-Redis扩展使用手册(一)

    //初始化redis实例 $redis = new Redis(); /* connect . open 链接redis * @param string host redis服务器地址 * @para ...

  6. How does Unity.Resolve know which constructor to use?

    Question: Given a class with several constructors - how can I tell Resolve which constructor to use? ...

  7. ANSI_NULLS和QUOTED_IDENTIFIER

    这些是 SQL-92 设置语句,使 SQL Server 2000/2005 遵从 SQL-92 规则. 当 SET QUOTED_IDENTIFIER 为 ON 时,标识符可以由双引号分隔,而文字必 ...

  8. JS正则表达式将url转成json格式

    var url = location.search.substr(1); param = {}; console.log(url); url.replace(/([^?&]+)=([^?&am ...

  9. 堆排序 Heapsort

    Prime + Heap 简直神了 时间优化好多,顺便就把Heapsort给撸了一发 具体看图 Heapsort利用完全二叉树+大(小)顶锥的结构每次将锥定元素和锥最末尾的元素交换 同时大(小)顶锥元 ...

  10. macos开发pgsql数据库

    mac安装Postgresql作为数据库 最简单的方式是安装Postgres.App. 这个应用里自带了最新版本的PostgreSQL而且不需要学习数据库服务器启动和关闭的命令.程序安好后(别忘了拖拽 ...