https://leetcode.com/problems/intersection-of-two-arrays/
nums1과 nums2를 비교하여 겹치는 값을 반환하는 문제이다
처음은 nums1을 탐색하면서 nums1의 값이 nums2에 있는지 탐색하는 방법으로 풀었다.
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
ans = []
for i in nums1:
if i not in ans and i in nums2:
ans.append(i)
return ans
참고로 중복이 나오면 안되기 때문에 이미 값이 ans에 있는지(not in ans) 확인하고 append해준다.
근데 일일이 탐색하는 방법이기 때문에 좀 오래걸리는 편인거같다
Runtime: 123 ms, faster than 5.56% of Python3 online submissions for Intersection of Two Arrays.
Memory Usage: 14 MB, less than 91.65% of Python3 online submissions for Intersection of Two Arrays.
차피 문제에서 겹치는 숫자만 파악하면 되기 때문에(ex. nums1[1,2,2,3] nums2[2,2,5]) 라는 케이스가 주어져도 [2,2]가 아닌 [2]만 반환하면 되기 떄문에 set함수를 이용하여 중복을 제거하여 찾아도 속도가 더 빨라진다
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return set(nums1) & set(nums2)
set함수로 중복되는 숫자를 제거한 후 비트연산자 &를 이용하여 중복된 숫자를 찾는 방법도 있다
Runtime: 56 ms, faster than 70.13% of Python3 online submissions for Intersection of Two Arrays.
Memory Usage: 14.1 MB, less than 68.55% of Python3 online submissions for Intersection of Two Arrays.
런타임면에서는 더 개선된 모습이다