[LeetCode] 2248. Intersection of Multiple Arrays

Chobby·2일 전
1

LeetCode

목록 보기
697/710

😎풀이

  1. nums 배열을 모두 Set 객체로 변환
  2. 변환된 Set 순회
    2-1. 현재 요소가 다른 요소에 존재하는지 검증
    2-2. 모든 배열에 존재 할 경우 교집합 목록에 추가
  3. 탐색된 교집합 배열 오름차 순 정렬
  4. 반환
function intersection(nums: number[][]): number[] {
    const sets = nums.map(a => new Set(a))
    const intersects = new Set<number>()
    for(let i = 0; i < sets.length; i++) {
        const curSet = sets[i]
        for(const num of curSet) {
            if(intersects.has(num)) continue
            let isValid = true
            for(let j = 0; j < sets.length; j++) {
                if(i === j) continue
                const otherSets = sets[j]
                if(otherSets.has(num)) continue
                isValid = false
                break
            }
            if(isValid) intersects.add(num)
        }
    }
    return [...intersects].toSorted((a, b) => a - b)
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글