풀이1
/**
* 350_IntersectionOfTwoArraysII.js
* Easy
* https://leetcode.com/problems/intersection-of-two-arrays-ii/
*/
var intersect = function(nums1, nums2) {
const answer = [], idxHash = {};
nums1.forEach((num) => {
const idx = idxHash[num] === undefined ? nums2.indexOf(num) : nums2.indexOf(num, idxHash[num] + 1);
if (idx > -1) {
idxHash[num] = idx;
answer.push(num);
}
});
return answer;
};
교집합을 구하는 문제로 hash 에 기존에 존재했던 값의 index 를 넣어두고 다음에 같은 값을 만났을 때 index + 1 부터 indexOf 로 해당 값이 있는지 확인하는 방식으로 해결했다.
풀이2 - 최적화
/**
* 350_IntersectionOfTwoArraysII.js
* Easy
* https://leetcode.com/problems/intersection-of-two-arrays-ii/
*/
var intersect = function(nums1, nums2) {
let small, big, answer = [], idxHash = {};
if (nums1.length <= nums2.length) {
small = nums1;
big = nums2;
} else {
small = nums2;
big = nums1;
}
small.forEach((num) => {
const idx = idxHash[num] === undefined ? big.indexOf(num) : big.indexOf(num, idxHash[num] + 1);
if (idx > -1) {
idxHash[num] = idx;
answer.push(num);
}
});
return answer;
};
해결 방법은 첫 번째 풀이와 동일하고, 교집합을 구하는 문제이므로 길이가 짧은 배열을 기준으로 겹치는 값을 찾으면 길이가 긴 배열을 기준으로 찾을 때보다 두 배열의 길이 차이만큼 연산 수를 줄일 수 있다.
'알고리즘 > LeetCode' 카테고리의 다른 글
[Leetcode][자바스크립트][Easy] 566. Reshape the Matrix (0) | 2022.01.09 |
---|---|
[Leetcode][자바스크립트][Easy] 121. Best Time to Buy and Sell Stock (0) | 2022.01.08 |
[Leetcode][자바스크립트][Easy] 88. Merge Sorted Array (0) | 2022.01.06 |
[Leetcode][자바스크립트][Easy] 53. Maximum Subarray (0) | 2022.01.05 |
[Leetcode][자바스크립트][Easy] 217. Contains Duplicate (0) | 2022.01.05 |
댓글