-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
8998c83
commit 3eff3d0
Showing
1 changed file
with
69 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
/** | ||
735. Asteroid Collision | ||
Solved | ||
Medium | ||
Topics | ||
Companies | ||
Hint | ||
We are given an array asteroids of integers representing asteroids in a row. | ||
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. | ||
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. | ||
**/ | ||
|
||
class AsteriodCollision { | ||
|
||
//mysolution | ||
public int[] asteroidCollision(int[] asteroids) { | ||
Stack<Integer> stack = new Stack<>(); | ||
|
||
for (int a : asteroids) { | ||
if (a > 0) { | ||
stack.push(a); | ||
} else { | ||
while (!stack.isEmpty() && stack.peek() > 0 && stack.peek() < -a) { | ||
stack.pop(); | ||
} | ||
|
||
if (stack.isEmpty() || stack.peek() < 0) { | ||
stack.push(a); | ||
} | ||
|
||
if (stack.peek() == -a) { | ||
stack.pop(); | ||
} | ||
} | ||
} | ||
|
||
int[] res = new int[stack.size()]; | ||
int i = stack.size() - 1; | ||
|
||
while(!stack.isEmpty()) { | ||
res[i--] = stack.pop(); | ||
} | ||
|
||
return res; | ||
} | ||
|
||
//best solution | ||
public int[] asteroidCollisionbest(int[] asteroids) { | ||
int previous = 0, current = 1; | ||
while (current < asteroids.length) { | ||
if (previous < 0 || asteroids[previous] < 0 || asteroids[current] > 0) { | ||
asteroids[++previous] = asteroids[current++]; | ||
} else if (asteroids[previous] == -asteroids[current]) { | ||
previous--; | ||
current++; | ||
} else if (asteroids[previous] > -asteroids[current]) { | ||
current++; | ||
} else { | ||
previous--; | ||
} | ||
} | ||
|
||
return previous < 0 ? new int[0] : Arrays.copyOfRange(asteroids, 0, previous + 1); | ||
} | ||
|
||
} |