Skip to content
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

feat: add swift implementation to lcp problem: No.12 #3752

Merged
merged 1 commit into from
Nov 12, 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
38 changes: 38 additions & 0 deletions lcp/LCP 12. 小张刷题计划/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,44 @@ function minTime(time: number[], m: number): number {
}
```

#### Swift

```swift
class Solution {
func minTime(_ time: [Int], _ m: Int) -> Int {
var left = 0
var right = time.reduce(0, +)

while left < right {
let mid = (left + right) / 2
if check(mid, time, m) {
right = mid
} else {
left = mid + 1
}
}
return left
}

private func check(_ t: Int, _ time: [Int], _ m: Int) -> Bool {
var sum = 0
var maxTime = 0
var days = 1

for x in time {
sum += x
maxTime = max(maxTime, x)
if sum - maxTime > t {
sum = x
maxTime = x
days += 1
}
}
return days <= m
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
33 changes: 33 additions & 0 deletions lcp/LCP 12. 小张刷题计划/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
class Solution {
func minTime(_ time: [Int], _ m: Int) -> Int {
var left = 0
var right = time.reduce(0, +)

while left < right {
let mid = (left + right) / 2
if check(mid, time, m) {
right = mid
} else {
left = mid + 1
}
}
return left
}

private func check(_ t: Int, _ time: [Int], _ m: Int) -> Bool {
var sum = 0
var maxTime = 0
var days = 1

for x in time {
sum += x
maxTime = max(maxTime, x)
if sum - maxTime > t {
sum = x
maxTime = x
days += 1
}
}
return days <= m
}
}
Loading