파이썬 알고리즘 인터뷰 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))
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)
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 를 했을 때 A가 True 이면 B가 반환되고 A가 False 이면 A가 그대로 반환되기 때문이다.