Intersection of Two Arrays II LeetCode solution in JavaScript

1
/**
2
* @param {number[]} nums1
3
* @param {number[]} nums2
4
* @return {number[]}
5
*/
6
var intersect = function (nums1, nums2) {
7
// initialize empty array
8
let result = [];
9

10
// sort arrays
11
const nums1Sorted = nums1.sort((a, b) => a - b);
12
const nums2Sorted = nums2.sort((a, b) => a - b);
13

14
let i = 0;
15
let j = 0;
16

17
while (i < nums1Sorted.length && j < nums2Sorted.length) {
18
// if nums1 index value is smaller than nums2 index value continue interating through nums1
19
if (nums1Sorted[i] < nums2Sorted[j]) {
20
i++;
21
// if nums1 index value is larger than nums2 index value continue interating through nums2
22
} else if (nums1Sorted[i] > nums2Sorted[j]) {
23
j++;
24
} else {
25
// if match found, push to result
26
result.push(nums1Sorted[i]);
27
i++;
28
j++;
29
}
30
}
31
return result;
32
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0