Skip to content

[jinah92] Week 1 #659

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

Merged
merged 2 commits into from
Dec 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions contains-duplicate/jinah92.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
keys = set()
for num in nums:
if num in keys:
return True
else:
keys.add(num)

return False
16 changes: 16 additions & 0 deletions house-robber/jinah92.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class Solution:
def rob(self, nums: List[int]) -> int:
memo = {}

def getAmount(start: int) -> int:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이번 기수에서 재귀호출 함수를 이용한 풀이는 처음 봤습니다 ㅎㅎㅎ
해당 풀이를 보면 memoization을 통해 시간복잡도를 최적화 시켰지만, 결국 재귀호출 스택의 깊이만큼 추가적인 공간복잡도가 소요된다는 것을 알 수 있는데요
시간이 좀 남았으니 반복문을 이용한 풀이도 도전해보시면 어떨까요?
재귀호출 풀이 <-> 반복문 풀이로 변환해보는 것은 알고리즘 문제 풀이에 있어서 큰 연습이 됩니다 :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저는 주로 재귀함수로 풀었는데 이번 기회에 dp로 풀이하는 방법을 알아보는 기회가 되었네요~

if not start < len(nums):
memo[start] = 0
Comment on lines +6 to +7
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

여기서 바로 리턴을 해도 되는 게 맞다면, 리턴을 추가하면 가독성과 효율성이 더 좋아질 거 같아요.

if start in memo:
return memo[start]

memo[start] = max(nums[start] + getAmount(start+2), getAmount(start+1))

return memo[start]

return getAmount(0)

18 changes: 18 additions & 0 deletions longest-consecutive-sequence/jinah92.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
result, last = 0, None
candidates = []
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

candidates라는 배열로 결과값 후보들을 관리하는 대신 result = max(result, candidate)처럼 결과값을 관리하는게 공간 측면에서 효율적일 것 같습니다

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

넵 최댓값 비교로 관리하는게 더 가독성도 좋고 효율적인 코드 작성이 될 것 같습니다!


for num in sorted(set(nums)):
if last is None or last + 1 == num:
result += 1
else:
candidates.append(result)
result = 1
last = num

if result is not 0:
candidates.append(result)
Comment on lines +14 to +15
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

위의 조건문으로 보아 result가 0일 때 candidates 배열에 들어갈 일은 없어 보여요. 제가 이해한 게 맞다면, 14번 라인은 필요없을 것 같습니다.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

14-15라인은 예외사항에 따라 추가되었습니다.
위 for문에서 가장 마지막 num에 접근하고 그 값이 직전 num보다 1보다 큰 경우, 첫번째 조건문만 타고 for순회문을 나오게 되는데 이 과정에서 candidates 리스트에 추가가 되지 않아 가장 최대 길이보다 1이 적은 결과값을 가지게 됩니다. 따라서 마지막에 누락된 result값을 추가하였습니다.

이 과정은 candidates 배열로 후보군을 업데이트하는 것보단 result 변수 하나만을 가지고 비교할 수 있어, 수정되면 리팩토링이 가능할거 같습니다 :)


return max(candidates) if len(candidates) > 0 else 0

12 changes: 12 additions & 0 deletions top-k-frequent-elements/jinah92.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
counters = {}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이왕 파이썬을 쓰실 거라면 collections 모듈의 defaultdict나 counter 컨테이너를 사용하시는게 더 좋을 것 같아요 ㅎㅎ

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

감사합니다! 제가 주언어는 타입스크립트지만 코테용으로 파이썬이 편리한거 같아서 선택했는데 좋은 기능이 있는지 몰랐네요


for num in nums:
if counters.get(num):
counters[num] += 1
else:
counters[num] = 1

return [val[0] for val in sorted(counters.items(), key=lambda x: x[1], reverse=True)[:k]]

19 changes: 19 additions & 0 deletions valid-palindrome/jinah92.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import re

class Solution:
def isPalindrome(self, s: str) -> bool:
replaced_string = re.sub(r"[^a-zA-Z0-9]", "", s).lower()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

python의 isalnum함수에 대해 찾아보시길 추천 드립니다


if len(replaced_string) == 0:
return True

start, end = 0, len(replaced_string)-1

while start <= len(replaced_string) // 2:
if replaced_string[start] is not replaced_string[end]:
return False

start += 1
end -= 1

return True
Loading