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.

Not good enough approach

var intersect = function(nums1, nums2) {
let r = [];
// get larger array
const len1 = nums1.length;
const len2 = nums2.length; // larger & smaller
const larger = len1 > len2 ? nums1: nums2;
const smaller = len1 > len2 ? nums2: nums1; // conver larger array to object
let hashed = {};
for (let n of larger) {
if (n in hashed) {
hashed[n]++;
} else {
hashed[n] = 1;
}
} // loop over smaller array
for (let n of smaller) {
if (`${n}` in hashed) {
r.push(n);
hashed[n] = hashed[n]-1;
if (hashed[n] === 0) {
delete hashed[n];
}
}
} return r;
};

The reason that code above is not good enough is because, \

1. we use larger array as lookup, this cause more memory usage. -- actually we need to use smaller array as lookup

2. we use 'len1, len2, samller, larger' extra storage, we can actully swap nums1 and nums by one extra function call.

var intersect = function(nums1, nums2) {

    if (nums1.length > nums2.length) {
return intersect(nums2, nums1);
} // conver samller array to object
let hashed = {};
for (let n of nums2) {
if (n in hashed) {
hashed[n]++;
} else {
hashed[n] = 1;
}
} let r = [];
// loop over smaller array
for (let n of nums1) {
if (hashed[n] > 0) {
r.push(n);
hashed[n] = hashed[n]-1;
}
} return r;
}

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?

Will write another post for the follow up questions.

最新文章

  1. Linux4:useradd、userdel、passwd、groupadd、chgrp、chown、df、du、sort、wget
  2. ubuntu14.04 server 安装vmware worktation 12
  3. Spring单实例、多线程安全、事务解析
  4. Duilib实现QQ聊天窗口晃动
  5. Integer
  6. Chart 点击获取坐标
  7. hdu 1081(最大子矩阵和)
  8. 我都使用了这些VS插件
  9. hdu 5437 Alisha’s Party 优先队列
  10. JZ2440开发笔记(7)——2440启动方式
  11. 关于闭包与for循环的理解
  12. maven入门(上)
  13. 9.Spark Streaming
  14. activiti-explore(activiti5.17) 替换数据库
  15. CMake在Visual Studio下保持目录结构
  16. js日期处理函数 -- 判断闰年,获取当月的总天数、添加月份
  17. 『计算机视觉』Mask-RCNN_推断网络其二:基于ReNet101的FPN共享网络暨TensorFlow和Keras交互简介
  18. this 指向问题ES5
  19. 【CSS】iconfont的使用
  20. (七)对Jmeter进行参数化的俩种方式

热门文章

  1. for循环中的switch的break和continue作用范围
  2. Python批量更改文件名
  3. 移动开发首页业界资讯移动应用平台技术专题 输入您要搜索的内容 基于Java Socket的自定义协议,实现Android与服务器的长连接(二)
  4. java基本数据类型的变量
  5. 前端不缓存,ajax不缓存,js操作cookie
  6. Jquery源码解析及案例分析
  7. altermanager使用报错
  8. 2019 荔枝java面试笔试题 (含面试题解析)
  9. div css字间距
  10. Java集合学习(3):HashSet