Skip to content

Commit c93288f

Browse files
authored
feat: add swift implementation to lcp problem: N9 (#3745)
1 parent 8ead911 commit c93288f

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed

lcp/LCP 09. 最小跳跃次数/README.md

+44
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,50 @@ func minJump(jump []int) int {
178178
}
179179
```
180180

181+
#### Swift
182+
183+
```swift
184+
class Solution {
185+
func minJump(_ jump: [Int]) -> Int {
186+
let n = jump.count
187+
var vis = Array(repeating: false, count: n)
188+
var queue = [0]
189+
vis[0] = true
190+
var ans = 0
191+
var maxReach = 1
192+
193+
while !queue.isEmpty {
194+
ans += 1
195+
let size = queue.count
196+
197+
for _ in 0..<size {
198+
let i = queue.removeFirst()
199+
200+
let forwardJump = i + jump[i]
201+
if forwardJump >= n {
202+
return ans
203+
}
204+
205+
if !vis[forwardJump] {
206+
queue.append(forwardJump)
207+
vis[forwardJump] = true
208+
}
209+
210+
while maxReach < i {
211+
if !vis[maxReach] {
212+
queue.append(maxReach)
213+
vis[maxReach] = true
214+
}
215+
maxReach += 1
216+
}
217+
}
218+
}
219+
220+
return -1
221+
}
222+
}
223+
```
224+
181225
<!-- tabs:end -->
182226

183227
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class Solution {
2+
func minJump(_ jump: [Int]) -> Int {
3+
let n = jump.count
4+
var vis = Array(repeating: false, count: n)
5+
var queue = [0]
6+
vis[0] = true
7+
var ans = 0
8+
var maxReach = 1
9+
10+
while !queue.isEmpty {
11+
ans += 1
12+
let size = queue.count
13+
14+
for _ in 0..<size {
15+
let i = queue.removeFirst()
16+
17+
let forwardJump = i + jump[i]
18+
if forwardJump >= n {
19+
return ans
20+
}
21+
22+
if !vis[forwardJump] {
23+
queue.append(forwardJump)
24+
vis[forwardJump] = true
25+
}
26+
27+
while maxReach < i {
28+
if !vis[maxReach] {
29+
queue.append(maxReach)
30+
vis[maxReach] = true
31+
}
32+
maxReach += 1
33+
}
34+
}
35+
}
36+
37+
return -1
38+
}
39+
}

0 commit comments

Comments
 (0)