LeetCode -Intersection of Two Arrays (투포인터, 이분탐색, 파이썬)
728x90
반응형
이진탐색으로 하나만 정렬하고 bisect으로 찾는 방법이 있고 투 포인터로 둘 다 정렬한 다음 같이 인덱스 0으로 시작해서 작은 배열의 인덱스를 1씩 증가시키는 방법이 있다.
중복이 없어야 되므로 set()을 사용한다
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums1.sort()
nums2.sort()
result=set()
i=j=0
while i<len(nums1) and j<len(nums2):
if nums1[i]<nums2[j]:
i+=1
elif nums1[i]>nums2[j]:
j+=1
else:
result.add(nums1[i])
i+=1
j+=1
return result
728x90
반응형
'Leetcode' 카테고리의 다른 글
[LeetCode] Fibonacci number (dp, 파이썬) (0) | 2020.10.21 |
---|---|
leetcode- single number(비트연산자, 파이썬) (0) | 2020.10.12 |
[LeetCode] 33. Search in Rotated Sorted Array (python, 이진탐색) 풀이 (0) | 2020.10.12 |
LeetCode - Array Partition 1 (0) | 2020.10.06 |
LeetCode. Group Anagrams (python) (0) | 2020.10.06 |
TAGS.