Skip to content

Commit 5f7fde0

Browse files
authored
feat: add swift implementation to lcof2 problem: No.037 (#3047)
1 parent 75eedb3 commit 5f7fde0

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

lcof2/剑指 Offer II 037. 小行星碰撞/README.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,33 @@ impl Solution {
221221
}
222222
```
223223

224+
#### Swift
225+
226+
```swift
227+
class Solution {
228+
func asteroidCollision(_ asteroids: [Int]) -> [Int] {
229+
var stack = [Int]()
230+
231+
for asteroid in asteroids {
232+
if asteroid > 0 {
233+
stack.append(asteroid)
234+
} else {
235+
while !stack.isEmpty && stack.last! > 0 && stack.last! < -asteroid {
236+
stack.removeLast()
237+
}
238+
if !stack.isEmpty && stack.last! == -asteroid {
239+
stack.removeLast()
240+
} else if stack.isEmpty || stack.last! < 0 {
241+
stack.append(asteroid)
242+
}
243+
}
244+
}
245+
246+
return stack
247+
}
248+
}
249+
```
250+
224251
<!-- tabs:end -->
225252

226253
<!-- solution:end -->
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
func asteroidCollision(_ asteroids: [Int]) -> [Int] {
3+
var stack = [Int]()
4+
5+
for asteroid in asteroids {
6+
if asteroid > 0 {
7+
stack.append(asteroid)
8+
} else {
9+
while !stack.isEmpty && stack.last! > 0 && stack.last! < -asteroid {
10+
stack.removeLast()
11+
}
12+
if !stack.isEmpty && stack.last! == -asteroid {
13+
stack.removeLast()
14+
} else if stack.isEmpty || stack.last! < 0 {
15+
stack.append(asteroid)
16+
}
17+
}
18+
}
19+
20+
return stack
21+
}
22+
}

0 commit comments

Comments
 (0)