File tree 2 files changed +41
-0
lines changed
2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change
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
+ } ;
Original file line number Diff line number Diff line change 237
237
722|[ Remove Comments] ( ./0722-remove-comments.js ) |Medium|
238
238
724|[ Find Pivot Index] ( ./0724-find-pivot-index.js ) |Easy|
239
239
733|[ Flood Fill] ( ./0733-flood-fill.js ) |Easy|
240
+ 735|[ Asteroid Collision] ( ./0735-asteroid-collision.js ) |Medium|
240
241
739|[ Daily Temperatures] ( ./0739-daily-temperatures.js ) |Medium|
241
242
746|[ Min Cost Climbing Stairs] ( ./0746-min-cost-climbing-stairs.js ) |Easy|
242
243
747|[ Largest Number At Least Twice of Others] ( ./0747-largest-number-at-least-twice-of-others.js ) |Easy|
You can’t perform that action at this time.
0 commit comments