[LeetCode] Intersection of Multiple Arrays

유승훈(Seunghun Yu)·2024년 3월 4일

Algorithm

목록 보기
9/9
post-thumbnail

난이도: EASY

문제 설명:
Given a string s consisting of lowercase English letters, return the first letter to appear twice.

참고사항:

  • A letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b.
  • s will contain at least one letter that appears twice.


문제를 보며 처음 한 생각


2차원 List에서 모든 row에 공통으로 나오는 요소들을 오름차순 리스트로 리턴하는 문제이다.

이는 2차원 List의 row수를 저장해둔 후,
각 row를 순회하면서 요소들을 dictionary에 key:요소, value: 요소 갯수로 저장을 한다.

마지막에 dictionary에서 value가 row수와 동일한 key들을 오름차순 리스트로 반환하면 될 것이라 생각하였다.

문제를 해결한 방법


from collections import defaultdict

파이썬 기본 dictionary보다 defaultdict를 사용하면 Keyerror를 발생시키지 않고, List에 있는 요소의 갯수를 셀 수 있다.

collect = defaultdict(int)
collect[nums[i][j]] += 1

이런식으로 Key: 초기값을 설정해두지 않아도 0으로 초기화 되어있어 Keyerror가 나지않아 코드를 줄일 수 있다.

다음은 전체 코드이다.
문제를 보며 처음 한 생각과 동일하게 구현하였다.

class Solution:
    def intersection(self, nums: List[List[int]]) -> List[int]:
        collect = defaultdict(int)
        row_length = len(nums)
        for i in range(row_length):
            for j in range(len(nums[i])):
                collect[nums[i][j]] += 1
        return sorted([k for k,v in collect.items() if v == row_length])

0개의 댓글