Given two arrays, write a function to compute their intersection.
This is a relatively common problem. The simplest way to compute the intersection of two arrays is to traverse nums1
and, for each element, traverse nums2
to check if the element exists in nums2
. This approach has a time complexity of O(mn). Here, we use the sorting and two-pointer approach. First, we sort the two arrays separately. Then, we set two pointers to traverse the arrays. We compare the elements pointed to by the two pointers. If one is smaller, we move that pointer forward. If one is larger, we move the other pointer forward. If they are equal, we first get the index of the last element in the target array. If the array is empty, it will be -1. In JavaScript, it will be undefined
, and it won't be equal in the comparison below. Then, we compare whether the last element is equal to the value pointed to by the pointer. If not, we add the value to the array, which is used for deduplication. Then we move both pointers forward. After the loop ends, we return the target array.