欣迪

出處: https://leetcode.com/problems/intersection-of-two-arrays/

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:

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

Constraints:

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000

找出兩個陣列中重疊的數字。

/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number[]}
 */
var intersection = function(nums1, nums2) {
  	// 兩個陣列都先去除重複的數字
    const set1 = new Set(nums1)
    const set2 = new Set(nums2)
    // 展開其中一個陣列進入迴圈
    const _set1 = [...set1]
    for (let i = 0; i < _set1.length; i++) {
      	// 如果沒有迴圈中的數字,就把該數字從組合中刪除
        if (!set2.has(_set1[i])) {
            set1.delete(_set1[i])
        }
    }
  	// 把結果展開
    return [...set1]
};

訂閱 IT-Monk

訂閱最新文章的發布消息! 😚😚😚
Loading

作者介紹 - 欣迪

欣迪

從設計到寫程式,發現自己有追求前端技巧的自虐傾向。不斷的踩坑,再從坑裡爬出來,慢慢對攀岩有點心得。 目前在多間公司擔任網站設計顧問。 同時也是網站架設公司負責人。