Skip to content

Commit

Permalink
Create AsteriodCollision.java
Browse files Browse the repository at this point in the history
  • Loading branch information
abhishektripathi66 authored Sep 24, 2024
1 parent 8998c83 commit 3eff3d0
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions Leetcode/AsteriodCollision.java
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);
}

}

0 comments on commit 3eff3d0

Please sign in to comment.