-
-
Notifications
You must be signed in to change notification settings - Fork 247
[sonjh1217] WEEK05 solutions #1837
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
class Solution { | ||
func maxProfit(_ prices: [Int]) -> Int { | ||
var maxProfit = 0 | ||
var minPrice = prices[0] | ||
|
||
for i in (1..<prices.count) { | ||
let profit = prices[i] - minPrice | ||
maxProfit = max(profit, maxProfit) | ||
minPrice = min(prices[i], minPrice) | ||
} | ||
|
||
return maxProfit | ||
|
||
//시간복잡도 O(n) | ||
//공간복잡도 O(1) | ||
} | ||
} | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
class Solution { | ||
func groupAnagrams(_ strs: [String]) -> [[String]] { | ||
var stringsByCount = [[Int]: [String]]() | ||
|
||
strs.map { str in | ||
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. map을 사용하셨는데, 반환값을 사용하지 않는 경우라면 forEach를 쓰면 의도가 더 잘 드러날 것 같습니다. 🙂 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. 그렇네요!! 사실 for loop만 많이 쓰다가 될수록 higher-order function을 써보려고 하고 있는데 초보 티가 났네용ㅎㅎ 감사합니다. 다음주 풀리에 반영해서 올릴게요~! |
||
var countsByAlphabet = Array(repeating: 0, count: 26) | ||
for char in str.unicodeScalars { | ||
countsByAlphabet[Int(char.value) - 97] += 1 | ||
} | ||
stringsByCount[countsByAlphabet, default: []].append(str) | ||
} | ||
|
||
return Array(stringsByCount.values) | ||
} | ||
//시간 O(n*L) L=string들의 평균 길이 | ||
//공간 O(n*L) | ||
} | ||
|
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.
minPrice가 prices[i]보다 큰 경우에만 minPrice를 업데이트 하면 어떨까요?
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.
If minPrice > prices[I] {
minPrice = prices[I]
}
요런 방식이 되겠네요! 사실 그러면 maxProfit = max(profit, maxProfit) 이 부분 역시
if profit > maxProfit {
maxProfit = profit
}
이렇게 될텐데요! 이 변경이 복잡도를 개선하는 것은 아니고, 업데이트를 덜 치기 때문에 약간 더 효율적이지만 min과 max가 주는 가독성이 저는 더 좋게 느껴져서 min, max 방식을 유지하려고 합니다. 디테일한 피드백 넘 감사합니다!