Skip to content

Commit d8dd2a9

Browse files
committed
feat: solve No.735
1 parent c5d037d commit d8dd2a9

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed

701-800/735. Asteroid Collision.md

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
# 735. Asteroid Collision
2+
3+
- Difficulty: Medium.
4+
- Related Topics: Array, Stack, Simulation.
5+
- Similar Questions: Can Place Flowers, Destroying Asteroids, Count Collisions on a Road, Robot Collisions.
6+
7+
## Problem
8+
9+
We are given an array `asteroids` of integers representing asteroids in a row.
10+
11+
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
12+
13+
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
14+
15+
 
16+
Example 1:
17+
18+
```
19+
Input: asteroids = [5,10,-5]
20+
Output: [5,10]
21+
Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
22+
```
23+
24+
Example 2:
25+
26+
```
27+
Input: asteroids = [8,-8]
28+
Output: []
29+
Explanation: The 8 and -8 collide exploding each other.
30+
```
31+
32+
Example 3:
33+
34+
```
35+
Input: asteroids = [10,2,-5]
36+
Output: [10]
37+
Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
38+
```
39+
40+
 
41+
**Constraints:**
42+
43+
44+
45+
- `2 <= asteroids.length <= 104`
46+
47+
- `-1000 <= asteroids[i] <= 1000`
48+
49+
- `asteroids[i] != 0`
50+
51+
52+
53+
## Solution
54+
55+
```javascript
56+
/**
57+
* @param {number[]} asteroids
58+
* @return {number[]}
59+
*/
60+
var asteroidCollision = function(asteroids) {
61+
var left = [];
62+
var right = [];
63+
for (var i = 0; i < asteroids.length; i++) {
64+
if (asteroids[i] > 0) {
65+
right.push(asteroids[i]);
66+
} else {
67+
while (true) {
68+
if (!right.length) {
69+
left.push(asteroids[i]);
70+
break;
71+
}
72+
const num = right[right.length - 1] || 0;
73+
if (num <= -asteroids[i]) right.pop();
74+
if (num >= -asteroids[i]) break;
75+
}
76+
}
77+
}
78+
return left.concat(right);
79+
};
80+
```
81+
82+
**Explain:**
83+
84+
nope.
85+
86+
**Complexity:**
87+
88+
* Time complexity : O(n).
89+
* Space complexity : O(n).

0 commit comments

Comments
 (0)