Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit b0f103b

Browse files
committed
Add solution #735
1 parent c4a7750 commit b0f103b

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

0735-asteroid-collision.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* 735. Asteroid Collision
3+
* https://leetcode.com/problems/asteroid-collision/
4+
* Difficulty: Medium
5+
*
6+
* We are given an array asteroids of integers representing asteroids in a row. The indices
7+
* of the asteriod in the array represent their relative position in space.
8+
*
9+
* For each asteroid, the absolute value represents its size, and the sign represents its
10+
* direction (positive meaning right, negative meaning left). Each asteroid moves at the
11+
* same speed.
12+
*
13+
* Find out the state of the asteroids after all collisions. If two asteroids meet, the
14+
* smaller one will explode. If both are the same size, both will explode. Two asteroids
15+
* moving in the same direction will never meet.
16+
*/
17+
18+
/**
19+
* @param {number[]} asteroids
20+
* @return {number[]}
21+
*/
22+
var asteroidCollision = function(asteroids) {
23+
const result = [];
24+
25+
for (let i = 0; i < asteroids.length; i++) {
26+
const previous = result[result.length - 1];
27+
const current = asteroids[i];
28+
29+
if (!result.length || previous < 0 || current > 0) {
30+
result.push(current);
31+
} else if (-current === previous) {
32+
result.pop();
33+
} else if (-current > previous) {
34+
result.pop();
35+
i--;
36+
}
37+
}
38+
39+
return result;
40+
};

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,7 @@
237237
722|[Remove Comments](./0722-remove-comments.js)|Medium|
238238
724|[Find Pivot Index](./0724-find-pivot-index.js)|Easy|
239239
733|[Flood Fill](./0733-flood-fill.js)|Easy|
240+
735|[Asteroid Collision](./0735-asteroid-collision.js)|Medium|
240241
739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium|
241242
746|[Min Cost Climbing Stairs](./0746-min-cost-climbing-stairs.js)|Easy|
242243
747|[Largest Number At Least Twice of Others](./0747-largest-number-at-least-twice-of-others.js)|Easy|

0 commit comments

Comments
 (0)