-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path350.js
58 lines (46 loc) · 1.58 KB
/
350.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// 350. Intersection of Two Arrays II
// https://leetcode.com/problems/intersection-of-two-arrays-ii/
const intersect = (nums1, nums2) => {
//## First solution with hash *(Faster)
// https://leetcode.com/submissions/detail/770227557/
// const list = {}
// let intersection = []
// nums1.forEach((num) => {
// if (!(`${num}` in list)) list[num] = 0
// list[num] += 1
// })
// nums2.forEach((num) => {
// if (`${num}` in list && list[num] != 0) {
// intersection.push(num)
// list[num] -= 1
// }
// })
// return intersection
// ## Two Pointer Solution
// https://leetcode.com/submissions/detail/770242797/
nums1.sort((a, b) => a - b)
nums2.sort((a, b) => a - b)
console.log("Nums1: ", nums1)
console.log("Nums2: ", nums2)
let i = 0, j = 0;
const intersection = []
while (i < nums1.length && j < nums2.length) {
if (nums1[i] === nums2[j]) {
intersection.push(nums1[i])
i++
j++
} else if (nums1[i] > nums2[j]) {
j++
} else {
i++
}
}
return intersection
}
// console.log(intersect([1,2,2,1], [2,2]))
// console.log(intersect([4,9,5],
// [9,4,9,8,4]))
console.log(intersect(
[61,24,20,58,95,53,17,32,45,85,70,20,83,62,35,89,5,95,12,86,58,77,30,64,46,13,5,92,67,40,20,38,31,18,89,85,7,30,67,34,62,35,47,98,3,41,53,26,66,40,54,44,57,46,70,60,4,63,82,42,65,59,17,98,29,72,1,96,82,66,98,6,92,31,43,81,88,60,10,55,66,82,0,79,11,81],
[5,25,4,39,57,49,93,79,7,8,49,89,2,7,73,88,45,15,34,92,84,38,85,34,16,6,99,0,2,36,68,52,73,50,77,44,61,48]))
// [5,4,57,79,7,89,88,45,34,92,38,85,6,0,77,44,61]