Given a 2D integer array nums where nums[i] is a non-empty array of distinct positive integers, return the list of integers that are present in each array of nums sorted in ascending order.
Example 1:
Input: nums = [[3,1,2,4,5],[1,2,3,4],[3,4,5,6]]
Output: [3,4]
Explanation:
The only integers present in each of nums[0] = [3,1,2,4,5], nums[1] = [1,2,3,4], and nums[2] = [3,4,5,6] are 3 and 4, so we return [3,4].
Example 2:
Input: nums = [[1,2,3],[4,5,6]]
Output: []
Explanation:
There does not exist any integer present both in nums[0] and nums[1], so we return an empty list [].
출처 : https://leetcode.com/problems/intersection-of-multiple-arrays/description/
풀이
function intersection(nums: number[][]): number[] {
let arr:number[]=nums[0];
for (let i=1;i<nums.length;i++){ arr=arr.filter(e => nums[i].indexOf(e) !== -1); }
return arr.sort((a,b)=>a-b);
};
여러 배열들에서 공통으로 존재하는 원소들을 찾아서 정렬된 배열로 반환하는 함수
arr=arr.filter(e => nums[i].indexOf(e) !== -1);
- 배열 arr의 요소들 중에서 현재 처리 중인 배열 nums[i]에 포함된 요소들만 남겨두는 역할
- arr.filter(e => ...):
- filter 메소드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열을 만든다.
- 여기서 arr는 현재까지의 교집합 배열
- e는 arr의 각 요소.
- nums[i].indexOf(e) !== -1:
- nums[i]는 현재 처리 중인 배열
- indexOf(e) 메소드는 배열 nums[i]에서 요소 e의 첫 번째 인덱스를 반환. 만약 요소 e가 배열 nums[i]에 없으면 -1을 반환
- nums[i].indexOf(e) !== -1는 요소 e가 배열 nums[i]에 존재하면 true를, 존재하지 않으면 false를 반환
예를 들어, arr가 [3, 1, 2, 4]이고, 현재 nums[i]가 [3, 4, 5, 6]인 경우
- e = 3: nums[i].indexOf(3) !== -1은 true (3은 nums[i]에 있음)
- e = 1: nums[i].indexOf(1) !== -1은 false (1은 nums[i]에 없음)
- e = 2: nums[i].indexOf(2) !== -1은 false (2는 nums[i]에 없음)
- e = 4: nums[i].indexOf(4) !== -1은 true (4는 nums[i]에 있음)
따라서, 필터링 후 arr는 [3, 4]
'LeetCode' 카테고리의 다른 글
| 2349. Design a Number Container System / TypeScript (0) | 2024.06.23 |
|---|---|
| 1219. Path with Maximum Gold / TypeScript (0) | 2024.06.22 |
| 283. Move Zeroes / TypeScript (0) | 2024.06.18 |
| 590. N-ary Tree Postorder Traversal / TypeScript (1) | 2024.06.18 |
| 1431. Kids With the Greatest Number of Candies / TypeScript (0) | 2024.06.16 |