DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Intersection of Array

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Explanation: [4,9] is also accepted.

/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number[]}
 */
var intersection = function (nums1, nums2) {
  let map = new Map();
  let intersectionArray = [];

  for (let i = 0; i < nums1.length; i++) {
    if (!map.has(nums1[i])) {
      map.set(nums1[i], 1);
    }
  }

  for (let i = 0; i < nums2.length; i++) {
    if (map.has(nums2[i]) && intersectionArray.indexOf(nums2[i]) === -1) {
      intersectionArray.push(nums2[i]);
    }
  }

  return intersectionArray;
};


Enter fullscreen mode Exit fullscreen mode

Top comments (0)