Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- binary search
- dfs
- linked list
- two pointers
- Medium
- sorting
- hash table
- DP
- 중간
- 이진트리
- 쉬움
- 문자열
- Binary
- easy
- 미디움
- Array
- tree
- backtracking
- binary tree
- 재귀
- HashTable
- list
- recursive
- 리트코드
- math
- string
- matrix
- Python
- leetcode
- Depth-first Search
Archives
- Today
- Total
부부의 코딩 성장 일기
LeetCode 349(Intersection of Two Arrays, Python) 본문
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) 가 있다.
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode 138(Copy List with Random Pointer, Python) (0) | 2024.03.24 |
---|---|
LeetCode 350(Intersection of Two Arrays II, Python) (1) | 2024.03.23 |
LeetCode 137(Single Number II, Python) (0) | 2024.03.21 |
LeetCode 131(Palindrome Partitioning, Python) (0) | 2024.03.15 |
LeetCode 326(Power of Three, Python) (0) | 2024.03.13 |