File tree Expand file tree Collapse file tree 2 files changed +49
-0
lines changed
lcof2/剑指 Offer II 037. 小行星碰撞 Expand file tree Collapse file tree 2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change @@ -221,6 +221,33 @@ impl Solution {
221
221
}
222
222
```
223
223
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
+
224
251
<!-- tabs: end -->
225
252
226
253
<!-- solution: end -->
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments