Their thinking
- First sort the two arrays.
- Starting at subscript 0, loop through each entry of the two arrays.
- If two comparison terms are equal, save the equal term and add one to the subscript to continue the comparison.
- If the two comparison terms are not equal, the lower value of the data subscript by one, continue the comparison.
- The loop ends and the stored data is returned.
code
/ * * *@param {number[]} nums1
* @param {number[]} nums2
* @return {number[]}* /
var intersect = function (nums1, nums2) {
// Sort first, then use double Pointers to get duplicates
nums1.sort((a, b) = > a - b)
nums2.sort((a, b) = > a - b)
let l = 0,
r = 0,
result = []
while (l < nums1.length && r < nums2.length) {
if (nums1[l] === nums2[r]) {
result.push(nums1[l])
l++
r++
} else if (nums1[l] < nums2[r]) {
l++
} else {
r++
}
}
return result
};
Copy the code