๋ฌธ์
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๋์