Algorithm/LeetCode
LeetCode 349(Intersection of Two Arrays, Python)
제로_콜라
2024. 3. 22. 19:00
1. 문제 링크
Intersection of Two Arrays - LeetCode
Can you solve this real interview question? Intersection of Two Arrays - Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
2. 문제 설명
- 두 개의 리스트가 주어졌을 때 중복된 요소를 담은 리스트를 반환하는 문제. 이때 반환하는 리스트에는 각 요소가 유니크해야함. 두 번 이상 나오면 안됨.
3. 처음 풀이
- 각 리스트를 집합으로 바꾸어 중복을 제거 후 두 집합을 교집합 연산 후 리스트로 바꾸어 반환
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return list(set(nums1) & set(nums2))
4. 다른 풀이
- 직접 첫번째 리스트를 순회하며 그 값이 두번째 리스트에 있고 아직 결과에 추가하지 않았다면 추가하기
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
r=[]
for i in range(len(nums1)):
if (nums1[i] in nums2 and nums1[i] not in r):
r.append(nums1[i])
return (r)
5. 배운 점
- 간단한 문제이다. 그럼에도 배운 점이라고 하면 두 집합 A, B의 교집합을 구할때
- 나는 A&B를 하였고
- 또 다른 방법으로는 A-(A-B), A.intersection(B), set.intersection(A, B) 가 있다.