본문 바로가기
코딩테스트/LeetCode

[Python][LeetCode] Intersection of Two Arrays(두 배열의 교집합)

by jungmin.park 2023. 11. 1.

https://leetcode.com/problems/intersection-of-two-arrays/description/

 

Intersection of Two Arrays - LeetCode

Can you solve this real interview question? Intersection of Two Arrays - Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.   Example 1: In

leetcode.com

문제 설명:

두 배열이 주어졌을때 교집합을 찾는 문제

 

투포인터

  • 2개의 배열을 집합으로 받아 정렬한다.
  • 배열 각각에 포인터를 두어 값이 같으면 결과 배열에 추가하고
  • 배열1 < 배열2 이면 배열1의 포인터값을 증가시켜준다.
  • 배열2 > 배열1 이면 배열2의 포인터값을 증가시켜준다.
        nums1 = sorted(list(set(nums1)))
        nums2 = sorted(list(set(nums2)))
        result = []
        p1 = p2 = 0
        while p1 < len(nums1) and p2 < len(nums2):
            if(nums1[p1] == nums2[p2]):
                result.append(nums1[p1])
                p1 += 1
                p2 += 1
            else:
                if(nums1[p1] < nums2[p2]):
                    p1 += 1
                else:
                    p2 += 1
        return result

 

 

in 사용

        result = set()
        for n1 in nums1:
            for n2 in nums2:
                if n1 == n2:
                    result.add(n1)
        return result

 

bisect 모듈 사용

        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 result

 

 

 

투포인터가 제일 빠르다.