Skip to content

[sun] WEEK 5 solution #450

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 7 commits into from
Sep 16, 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
25 changes: 25 additions & 0 deletions 3sum/sun912.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""
TC: O(n^2)
SC: O(1)
"""

class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
result = set()
nums.sort()

for i in range(len(nums)-2):
left,right = i+1, len(nums)-1
while left < right:
three_sum = nums[i]+nums[left]+nums[right]

if three_sum < 0:
left += 1
elif three_sum > 0:
right -= 1
else:
result.add((nums[i], nums[left], nums[right]))
left,right = left+1, right-1

return list(result)
Copy link
Contributor

@leokim0922 leokim0922 Sep 14, 2024

Choose a reason for hiding this comment

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

코드 전반적인 내용은 잘 이해가 됩니다만, 요 부분이 조금 신경이 쓰이네요 ㅎㅎ 혹시 result를 시작부터 list로 작성하는 방법도 생각해보셨을까요? 캐스팅을 하더라도 Time complexity가 유의미한 변화가 없는건 이해가 갑니다만, set을 사용하지 않으면 메모리 측면에서 조금 유리하지 않을까 생각이 드네요 😃


21 changes: 21 additions & 0 deletions best-time-to-buy-and-sell-stock/sun912.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""
TC: O(n)
SC: O(1)
"""
class Solution:
def maxProfit(self, prices: List[int]) -> int:
max_profit= 0
l = 0
r = 1

while r < len(prices):
Copy link
Contributor

Choose a reason for hiding this comment

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

코드 내용 잘 보았습니다! two pointer를 이용한 솔루션 자체는 이해가 잘 되는데요 아래와 같은 방법으로 조금 더 간결하게 적을 수 있지 않을까 싶어 코멘트 드립니다 😄

max_profit=0
buy = 0 ## l,r 대신 사는날의 인덱스만 표기

for sell in range(1, len(prices)): ## while loop 대신 for loop을 이용해서 sell 포인터를 안으로 포함시켜버리기

이렇게 개선하면 조금 더 간결하게 쓸 수 있을거 같아요!

if prices[l] < prices[r]:
profit = prices[r] - prices[l]
max_profit = max(max_profit, profit)

else:
l = r
r +=1
return max_profit


19 changes: 19 additions & 0 deletions group-anagrams/sun912.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"""
TC: O(m*n)
SC: O(26*n) -> O(n)
"""

from collections import defaultdict

class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
result = defaultdict(list)

for word in strs:
count = [0] * 26

for c in word:
count[ord(c)-ord("a")] += 1
result[tuple(count)].append(word)

return result.values()