LeetCode 349. Intersection of Two Arrays

개발공부를해보자·2025년 2월 25일

LeetCode

목록 보기
67/95

파이썬 알고리즘 인터뷰 67번(리트코드 349번) Intersection of Two Arrays
https://leetcode.com/problems/intersection-of-two-arrays/

나의 풀이

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        return list(set(nums1) & set(nums2))

다른 풀이1(이진 검색)

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        result = set()
        nums2.sort()
        for n1 in nums1:
            i2 = bisect.bisect_left(nums2, n1)
            if len(nums2) > 0 and len(nums2) > i2 and n1 == nums2[i2]:
                result.add(n1)
        return list(result)

다른 풀이2(Two Pointers)

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        result = set()
        nums1.sort()
        nums2.sort()
        i = j = 0

        while i < len(nums1) and j < len(nums2):
            if nums1[i] > nums2[j]:
                j += 1
            elif nums1[i] < nums2[j]:
                i += 1
            else:
                result.add(nums1[i])
                i += 1
                j += 1

        return list(result)

배운 점

# 논리 연산자 A and B: A가 False이면 A를 그대로 반환, A가 True이면 B를 반환
print([] and [1, 2, 3])     # [] (A가 False이므로 그대로 반환)
print([0] and [1, 2, 3])    # [1, 2, 3] (A가 True이므로 B 반환)
print(set() and {1, 2})     # set() (A가 False이므로 그대로 반환)
print({1} and {2, 3})       # {2, 3} (A가 True이므로 B 반환)

# 두 집합이나 배열 사이에 and를 연결했을 때 결과
print(set([4, 9, 5]) and set([9, 4, 9, 8, 4]))   # {4, 8, 9} (첫 번째가 True이므로 두 번째 반환)
print([1, 2] and [3, 4])                         # [3, 4] (첫 번째가 True이므로 두 번째 반환)
print([] and [3, 4])                             # [] (첫 번째가 False이므로 그대로 반환)

# 두 집합 사이의 논리 연산자 and vs 집합 연산자 &
a = {4, 9, 5}
b = {9, 4, 9, 8, 4}

print(a and b)  # {4, 8, 9} (논리 연산자 and: a가 True이므로 b 반환)
print(a & b)    # {4, 9} (집합 연산자 &: 교집합 반환)
  • 두 집합의 교집합 연산이 &인데 호기심에 and로 바꾸어 보았더니 예상과 달리 True 가 아닌 집합이 반환되었다.
  • A and B 를 했을 때 ATrue 이면 B가 반환되고 AFalse 이면 A가 그대로 반환되기 때문이다.
  • 이 내용을 아래 글에 자세히 정리해보았다.

파이썬 and 연산자와 & 연산자의 미묘한 차이

profile
개발 공부하는 30대 비전공자 직장인

0개의 댓글