개발/πŸ’¬ μ½”λ”©ν…ŒμŠ€νŠΈ

[leetCode] 2215. Find the Difference of Two Arrays

밍(Ming) 🐈‍⬛ 2024. 1. 30. 15:14
728x90
λ°˜μ‘ν˜•

문제

Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where:

  • answer[0] is a list of all distinct integers in nums1 which are not present in nums2.
  • answer[1] is a list of all distinct integers in nums2 which are not present in nums1.

Note that the integers in the lists may be returned in any order.

 

Example 1:

Input: nums1 = [1,2,3], nums2 = [2,4,6]
Output: [[1,3],[4,6]]
Explanation:
For nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3].
For nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums2. Therefore, answer[1] = [4,6].

 

 

 

 

ν•΄κ²°λ°©ν–₯

μ£Όμ–΄μ§„ 두 개의 λ°°μ—΄μ—μ„œ ꡐ집합을 μ°Ύμ•„λ‚΄μ„œ 각각의 λ°°μ—΄μ—μ„œ κ΅μ§‘ν•©λ§Œ μ œκ±°ν•΄μ£Όλ©΄ λ˜μ§€ μ•Šλ‚˜? 라고 생각을 ν–ˆλ‹€. 

κ·Έλž˜μ„œ μ²˜μŒμ— μž‘μ„±ν–ˆλ˜ 잘 λͺ» 된 해결법은 μ•„λž˜μ— μžˆλ‹€. μ΄ˆμ•ˆμ€ μ•„λž˜μ˜ μ½”λ“œλŠ” μ•„λ‹˜. ν…ŒμŠ€νŠΈ μ½”λ“œ λͺ‡κ°œλŠ” ν†΅κ³Όν•˜κ³  λͺ‡ κ°œλŠ” 톡과 λͺ» ν•΄μ„œ λ‹€μ‹œ μž‘μ„±ν•˜λ‹€κ°€ λ³€κ²½λœκ²Œ μ•„λž˜μ™€ κ°™μŒ. μ€‘λ³΅λ˜λŠ” ꡐ집합이 μžˆμ„μˆ˜λ„ μžˆλ‹€λŠ” 사싀을 생각 λͺ» 함. 

 

    let duplicated = []
    
    nums1 = new Set(nums1);
    nums2 = new Set(nums2);
    const n1 = Array.from(nums1)
    const n2 = Array.from(nums2)
    
    for(let i=0; i<n1.length; i++){
        for(let j=0; j<n2.length; j++ ){
            if(n1[i] == n2[j]){
                duplicated.push(n1[i])
            }
        }
    }
    
    const set = new Set(duplicated);
    const dupArr = [...set]
    
    console.log(dupArr)
    const temp1 = n1.filter((v) => dupArr.some((item) => item !== v ? v : ''))
    const temp2 = n2.filter((v) => dupArr.some((item) => item !== v ? v : ''))
                                                       
     console.log(temp1, temp2)
    
    return [temp1, temp2]

 

 

 

 

 

μ†”λ£¨μ…˜ 

var findDifference = function(nums1, nums2) {
    const set1 = new Set(nums1);
    const set2 = new Set(nums2);
    return [
        Array.from(set1).filter(n => !set2.has(n)),
        Array.from(set2).filter(n => !set1.has(n)),
    ]

};

 

Set.prototype.has() 을 μ‚¬μš©ν•˜λ©΄ Set κ°μ²΄μ— μ£Όμ–΄μ§„ μš”μ†Œκ°€ μ‘΄μž¬ν•˜λŠ”μ§€ μ—¬λΆ€λ₯Ό νŒλ³„ν•΄ λ°˜ν™˜ν•©λ‹ˆλ‹€.

κ·Έλž˜μ„œ set1 λ°°μ—΄ μš”μ†Œλ₯Ό ν•˜λ‚˜ν•˜λ‚˜ set2에 λŒ€μž…ν•΄μ„œ μžˆλ‚˜ μ—†λ‚˜ νŒλ³€ν•΄μ„œ μ—†λŠ” κ²ƒλ§Œ filterν•˜κ²Œ ν•©λ‹ˆλ‹€. μ—­μ‹œλ‚˜ set2λ„μš”

 

 

 

 

 

 

728x90