[LeetCode] Find the Difference of Two Arrays
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 nums1. Therefore, answer[1] = [4,6].
Example 2:
Input: nums1 = [1,2,3,3], nums2 = [1,1,2,2]
Output: [[3],[]]
Explanation:
For nums1, nums1[2] and nums1[3] are not present in nums2.
Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3].
Every integer in nums2 is present in nums1. Therefore, answer[1] = [].
Constraints:
1 <= nums1.length, nums2.length <= 1000
-1000 <= nums1[i], nums2[i] <= 1000
숫자 배열이 두 개 주어지고, [[], []] 형식으로 리턴해야 함.
앞 배열에는 nums2에 없고 nums1에만 있는 숫자를 넣고 뒷 배열도 동일함.
리턴할 배열은 정렬할 필요 없음
const findDifference = function(nums1, nums2) {
const numSet1 = new Set(nums1);
const numSet2 = new Set(nums2);
const result = [[], []];
result[0] = [...numSet1.difference(numSet2)];
result[1] = [...numSet2.difference(numSet1)];
return result;
};
단순히 set으로 바꿔서 중복 숫자를 지워주고,
set.difference로 차집합을 구해 다시 배열로 바꿔 결과에 넣어 리턴해 줬다.
처음에는 new Array(...numSet1.difference(numSet2)] 이렇게 했는데,
결과가 [ , , ] 이런식으로 나오길래 찾아보니...
set에 숫자가 한 개만 있어서 [3] 이런식으로 돼있을 때 스프레드 연산자(...)를 쓰면 3 하나로 인식이 된다.
결과적으로 그냥 길이가 3인 빈 배열을 만들게 되는 것이다~.~ 그걸 방지하려면 그냥 대괄호 안에 스프레드 연산자를 쓰면 된다.
효율이 쪼끔 더 높은 솔루션을 찾아보니 아래처럼 filter로 바로 배열로 만들어주는 방식이었다.
var findDifference = function(nums1, nums2) {
const set1 = new Set(nums1);
const set2 = new Set(nums2);
const onlyIn1 = [...set1].filter(x=>!set2.has(x));
const onlyIn2 = [...set2].filter(x=>!set1.has(x));
return[onlyIn1,onlyIn2];
};
로직상 큰 차이는 없을 것 같은데 왜일까 싶었다.
개인적으로는 diffrenece가 가독성도 더 좋고 깔끔해 보이는데.
보니까.. difference는 2024년 6에 새롭게 Set.prototype에 추가된 함수인데
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/difference
그래서 비교적 최근에 나온 메서드라 아직 최적화가 덜 되어서 그럴려나? 싶은 추측.....ㅇ<-<
시기에 따라서는 새로 나온 더 편한 메서드가 무조건 또 효율적이기만 한 건 아닐 수 있구나 싶다.
'코테연습' 카테고리의 다른 글
[LeetCode] Unique Number of Occurrences (0) | 2025.04.24 |
---|---|
[LeetCode] Find Pivot Index (0) | 2025.04.22 |
[LeetCode] Find the Highest Altitude (0) | 2025.04.21 |