Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces Swift solutions for three algorithmic challenges: 'Most Received Gift', 'Donut and Bar Graph', and 'Mountain Tiling'. The review feedback focuses on performance and code quality improvements, specifically suggesting the use of a dictionary for O(1) index lookups to avoid O(N) overhead in loops, adhering to Swift style conventions by avoiding semicolons in variable declarations, and optimizing the space complexity of the dynamic programming solution from O(N) to O(1).
|
|
||
| for gift in gifts { | ||
| let line = gift.split(separator: " ").map { String($0) } | ||
| let sender = friends.firstIndex(of: line[0])! | ||
| let receiver = friends.firstIndex(of: line[1])! |
There was a problem hiding this comment.
friends.firstIndex(of:)는 배열을 순회하므로 gifts 루프 내에서 반복 호출하면 전체 시간 복잡도가
| for gift in gifts { | |
| let line = gift.split(separator: " ").map { String($0) } | |
| let sender = friends.firstIndex(of: line[0])! | |
| let receiver = friends.firstIndex(of: line[1])! | |
| let friendIndex = Dictionary(uniqueKeysWithValues: friends.enumerated().map { ($1, $0) }) | |
| for gift in gifts { | |
| let line = gift.split(separator: " ").map { String($0) } | |
| let sender = friendIndex[line[0]]! | |
| let receiver = friendIndex[line[1]]! |
| import Foundation | ||
|
|
||
| func solution(_ edges: [[Int]]) -> [Int] { | ||
| var donut = 0; var stick = 0; var eight = 0 |
| var dp1 = [Int](repeating: 0, count: n+1) | ||
| var dp2 = [Int](repeating: 1, count: n+1) | ||
|
|
||
| for index in 1...n { | ||
| dp1[index] = (dp1[index - 1] + dp2[index - 1]) % 10007 | ||
| if tops[index - 1] == 1 { | ||
| dp2[index] = (dp1[index - 1] * 2 + dp2[index - 1] * 3) % 10007 | ||
| } | ||
| else { | ||
| dp2[index] = (dp1[index - 1] + dp2[index - 1] * 2) % 10007 | ||
| } | ||
| } | ||
| return (dp1[n] + dp2[n]) % 10007 |
There was a problem hiding this comment.
현재 DP 풀이는
var dp1 = 0
var dp2 = 1
for top in tops {
let prevDp1 = dp1
let prevDp2 = dp2
dp1 = (prevDp1 + prevDp2) % 10007
if top == 1 {
dp2 = (prevDp1 * 2 + prevDp2 * 3) % 10007
} else {
dp2 = (prevDp1 + prevDp2 * 2) % 10007
}
}
return (dp1 + dp2) % 10007
🔗 문제 링크
✔️ 소요된 시간
4시간