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
- Elasticsearch
- git
- 오버로딩
- overriding
- elastic certified engineer
- dlfks
- 버전관리
- 상속
- Overloading
- java
- 오버라이딩
- 형상관리
Archives
- Today
- Total
엔지니어 블로그
[Leetcode]2657. Find the Prefix Common Array of Two Arrays 본문
풀이
배열 B에 배열 A의 원소 값이 몇번이나 포함되어 있는지 확인하면 되는 문제다.
이 문제는 처음에 for문을 가지고 간단히 구현해봤는데, 정답은 맞았지만 2번의 for문으로 인해 복잡도가 높아져 응답시간이 느린 코드가 되었다.
그래서 솔루션을 살짝 보니 훨씬 간단한 방법이 있었다.
코드
#정답코드
class Solution:
def findThePrefixCommonArray(self, A: List[int], B: List[int]) -> List[int]:
n = len(A)
ans = []
seen = [0] * (n + 1)
common = 0
for i in range(n):
if seen[A[i]] == 0:
seen[A[i]] = 1
elif seen[A[i]] == 1:
common += 1
if seen[B[i]] == 0:
seen[B[i]] = 1
elif seen[B[i]] == 1:
common += 1
ans.append(common)
return ans
#느린코드
class Solution:
def findThePrefixCommonArray(self, A: list[int], B: list[int]) -> list[int]:
N = len(A)
ans = []
cnt = 0
for n in range(N):
cnt = 0
for a in A[:n+1]:
if a in B[:n+1]:
cnt += 1
ans.append(cnt)
return ans
'알고리즘' 카테고리의 다른 글
[Leetcode] 392.Is Subsequence (0) | 2025.02.12 |
---|---|
[LeetCode] 1. Two Sum (0) | 2025.02.01 |
[Leetcode] 916. Word Subsets (0) | 2025.01.10 |
[Leetcode]2006. Count Number of Pairs With Absolute Difference K (0) | 2025.01.04 |
[Leetcode]1941. Check if All Characters Have Equal Number of Occurrences (0) | 2025.01.04 |