Skip to content

Commit 8ead911

Browse files
authored
feat: add swift implementation to lcp problem: No.08 (#3744)
1 parent 6edb8f6 commit 8ead911

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

lcp/LCP 08. 剧情触发时间/README.md

+41
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,47 @@ class Solution {
140140
}
141141
```
142142

143+
#### Swift
144+
145+
```swift
146+
class Solution {
147+
func getTriggerTime(_ increase: [[Int]], _ requirements: [[Int]]) -> [Int] {
148+
let m = increase.count, n = requirements.count
149+
var s = Array(repeating: [0, 0, 0], count: m + 1)
150+
151+
for i in 0..<m {
152+
for j in 0..<3 {
153+
s[i + 1][j] = s[i][j] + increase[i][j]
154+
}
155+
}
156+
157+
var ans = Array(repeating: -1, count: n)
158+
for i in 0..<n {
159+
var left = 0, right = m + 1
160+
while left < right {
161+
let mid = (left + right) / 2
162+
if check(s[mid], requirements[i]) {
163+
ans[i] = mid
164+
right = mid
165+
} else {
166+
left = mid + 1
167+
}
168+
}
169+
}
170+
return ans
171+
}
172+
173+
private func check(_ a: [Int], _ b: [Int]) -> Bool {
174+
for i in 0..<3 {
175+
if a[i] < b[i] {
176+
return false
177+
}
178+
}
179+
return true
180+
}
181+
}
182+
```
183+
143184
<!-- tabs:end -->
144185

145186
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
func getTriggerTime(_ increase: [[Int]], _ requirements: [[Int]]) -> [Int] {
3+
let m = increase.count, n = requirements.count
4+
var s = Array(repeating: [0, 0, 0], count: m + 1)
5+
6+
for i in 0..<m {
7+
for j in 0..<3 {
8+
s[i + 1][j] = s[i][j] + increase[i][j]
9+
}
10+
}
11+
12+
var ans = Array(repeating: -1, count: n)
13+
for i in 0..<n {
14+
var left = 0, right = m + 1
15+
while left < right {
16+
let mid = (left + right) / 2
17+
if check(s[mid], requirements[i]) {
18+
ans[i] = mid
19+
right = mid
20+
} else {
21+
left = mid + 1
22+
}
23+
}
24+
}
25+
return ans
26+
}
27+
28+
private func check(_ a: [Int], _ b: [Int]) -> Bool {
29+
for i in 0..<3 {
30+
if a[i] < b[i] {
31+
return false
32+
}
33+
}
34+
return true
35+
}
36+
}

0 commit comments

Comments
 (0)