-
-
Notifications
You must be signed in to change notification settings - Fork 361
[yuseok89] WEEK 05 Solutions #2765
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
dc34f93
96a81aa
04a8b21
b8d817a
82f26dc
ac3a659
b5f763d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 최소값과 최대 이익을 변수로 추적해 한 번의 스캔으로 해결함. 추가 데이터 구조 없이도 된다. 개선 제안: 현재 구현이 적절해 보입니다. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| # TC: O(N) | ||
| # SC: O(1) | ||
| class Solution: | ||
| def maxProfit(self, prices: List[int]) -> int: | ||
| min_until_now = prices[0] | ||
| max_profit = 0 | ||
|
|
||
| for price in prices: | ||
| profit = price - min_until_now | ||
|
|
||
| if profit > max_profit: | ||
| max_profit = profit | ||
|
|
||
| if price < min_until_now: | ||
| min_until_now = price | ||
|
|
||
| return max_profit | ||
|
|
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 각 문자열의 길이 k에 대해 정렬 비용이 필요하지만, 총 n개 문자열에 대해 합리적이다. 개선 제안: 현재 구현이 적절해 보입니다. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| # TC: O(N * LlogL) | ||
| # SC: O(N * L) | ||
| class Solution: | ||
| def groupAnagrams(self, strs: List[str]) -> List[List[str]]: | ||
|
|
||
| ans = defaultdict(list) | ||
|
|
||
| for s in strs: | ||
| ans[''.join(sorted(s))].append(s) | ||
|
|
||
| return list(ans.values()) | ||
|
|
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 각 트라이 노드는 해시맵으로 자식 노드를 관리하며, 단어 길이 m에 비례한 시간과 공간이 필요하다. 개선 제안: 현재 구현이 적절해 보입니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| # TC: O(L) | ||
| # SC: O(L * N) | ||
| class TrieNode: | ||
| def __init__(self): | ||
| self.next = {} | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 요건 타입 힌트를 명확하게 지정해주면 더 좋을 거 같습니다. |
||
| self.is_end = False | ||
|
|
||
| class Trie: | ||
|
|
||
| def __init__(self): | ||
| self.root = TrieNode() | ||
|
|
||
| def insert(self, word: str) -> None: | ||
| cur = self.root | ||
|
|
||
| for c in word: | ||
| if c not in cur.next: | ||
| cur.next[c] = TrieNode() | ||
|
|
||
| cur = cur.next[c] | ||
|
|
||
| cur.is_end = True | ||
|
|
||
| def search(self, word: str) -> bool: | ||
| cur = self.root | ||
|
|
||
| for c in word: | ||
| if c not in cur.next: | ||
| return False | ||
|
|
||
| cur = cur.next[c] | ||
|
|
||
| return cur.is_end | ||
|
|
||
| def startsWith(self, prefix: str) -> bool: | ||
| cur = self.root | ||
|
|
||
| for c in prefix: | ||
| if c not in cur.next: | ||
| return False | ||
|
|
||
| cur = cur.next[c] | ||
|
|
||
| return True | ||
|
|
||
|
|
||
| # Your Trie object will be instantiated and called as such: | ||
| # obj = Trie() | ||
| # obj.insert(word) | ||
| # param_2 = obj.search(word) | ||
| # param_3 = obj.startsWith(prefix) | ||
|
|
||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 문제의 핵심적인 부분만 딱 캐치해서 푸신 거 같습니다. 아이디어는 어떻게 얻으셨는지 궁금하네요. 비슷하게 접근해서 푸셨던 문제나 경험이 있으실까요?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 글세요.. 굳이 따지자면 제가 있는 회사에 내부 테스트가 있는데 스타일이 비슷한 문제인 것 같긴 합니다..
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🏷️ 알고리즘 패턴 분석
📊 시간/공간 복잡도 분석
피드백: 단어 길이 구간을 기반으로 재귀 탐색과 방문 기록으로 중복 계산을 피한다. 개선 제안: 현재 구현이 적절해 보입니다.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| class Solution: | ||
| def wordBreak(self, s: str, wordDict: List[str]) -> bool: | ||
|
|
||
| word_set = set() | ||
| word_lens = set() | ||
|
|
||
| for word in wordDict: | ||
| word_set.add(word) | ||
| word_lens.add(len(word)) | ||
|
|
||
| word_lens = sorted(word_lens) | ||
| visited = set() | ||
|
|
||
| def rec(cur): | ||
| if cur in visited: | ||
| return False | ||
|
|
||
| if len(cur) == 0: | ||
| return True | ||
|
|
||
| for l in word_lens: | ||
| if len(cur) < l: | ||
| return False | ||
|
|
||
| if cur[0:l] in word_set: | ||
| if rec(cur[l:]): | ||
| return True | ||
|
|
||
| visited.add(cur) | ||
|
|
||
| return False | ||
|
|
||
| return rec(s) | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
prices[1:]
와 같이 하시면 보기엔 정말 좋은데 말이죠
파이썬 슬라이싱은 말 그대로 배열을 하나 더 만들어서 사용하는거라 이 간단한 과정에만 O(N)의 시간이 소요되어요!
파이썬 시간복잡도
Get slice 부분을 보시면 O(k) 라는것을 알수 있죠
그래서 좀 귀찮으시더라도
range(1, len(prices))를 쓰시는게 나으실거에요!
물론 지금같은 경우는 전체 시간복잡도가 O(N)이고 저 연산은 단 한번 실행되니 시간복잡도 자체에는 큰 영향을 주진 않겠지만
for loop 안에서 써야하는 일이 생긴다면 좀 다르겠죠
word-break 문제에서 이부분을 잘 생각해 다른방식으로 최적화 할수 있는 부분이 있으니 한번 생각하면서 해보시면 좋을것 같네요!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
그리고
best time to buy and sell stock, 즉 해당 문제는
뒤에 로마 숫자를 붙혀서 1, 2, 3, 4, 5 총 다섯종류가 있는데요
dp 연습하기에 정말 괜찮은 문제라고 생각해서
2번문제
II는 한번 풀어보시길 추천드려요!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
감사합니다. 많이 배웁니다.
로직상 제거해도 괜찮고, range 보다 미묘하게 슬라이스 제거한 것이 빨라, 슬라이스 제거 버전으로 수정했습니다.