Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d09d906

Browse files
a-khakimova.khakimov
authored and
a.khakimov
committed
735. Asteroid Collision
1 parent ca162df commit d09d906

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
object Solution {
2+
def asteroidCollision(asteroids: Array[Int]): Array[Int] = {
3+
val stack = scala.collection.mutable.Stack.empty[Int]
4+
for (asteroid <- asteroids) {
5+
if (asteroid > 0) {
6+
stack.push(asteroid)
7+
} else {
8+
while (stack.nonEmpty && stack.top > 0 && stack.top < -asteroid) {
9+
stack.pop()
10+
}
11+
if (stack.nonEmpty && stack.top == -asteroid) {
12+
println(s"top=${stack.top} asteroid=$asteroid")
13+
stack.pop()
14+
} else if (stack.isEmpty || stack.top < 0) {
15+
stack.push(asteroid)
16+
}
17+
}
18+
}
19+
stack.toArray.reverse
20+
}
21+
}
22+
23+
Solution.asteroidCollision(Array(5,10,-5)) // [5,10]
24+
Solution.asteroidCollision(Array(8,-8)) // []
25+
Solution.asteroidCollision(Array(10,2,-5)) // [10]
26+
Solution.asteroidCollision(Array(-2,-1,1,2)) // [-2,-1,1,2]
27+
Solution.asteroidCollision(Array(-3,-2,-1,1,2,3)) // [-3,-2,-1,1,2,3]
28+
Solution.asteroidCollision(Array(3,2,1,-1,-2,-3)) // []
29+
Solution.asteroidCollision(Array(-2,2,-1,-2)) // [-2]
30+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /