public int[] asteroidCollision(int[] asteroids) { Stack<Integer> st = new Stack<>(); int…
- User
public int[] asteroidCollision(int[] asteroids) { Stack st = new Stack<>(); int n = asteroids.length; int i=0; while(i < n){ if(asteroids[i] < 0){ if(st.size()==0 || st.peek()<0){ st.push(asteroids[i]); i++; } else if(st.peek() == Math.abs(asteroids[i])){ st.pop(); i++; } else if(st.peek()< Math.abs(asteroids[i])){ st.pop(); } else if(st.peek() > Math.abs(asteroids[i])){ i++; } }else{ st.push(asteroids[i]); i++; } } int[] ans = new int[st.size()]; for(int j=ans.length-1;j>=0;j--){ ans[j] = st.pop();
} return ans; } Why this code works but not my code (given below) what is the main error in my code: import java.util.Stack;
public class AsteroidCollision { public static int[] asteroidCollision(int[] asteroids) { if (asteroids.length == 0) return new int[0]; int i = 0; Stack st = new Stack<>(); while (i < asteroids.length) { if (asteroids[i] > 0) { st.push(asteroids[i]); i++;
} else { if (st.size() == 0 || st.peek() > 0) { if (st.peek() > Math.abs(asteroids[i])) { i++; } else if (st.peek() < Math.abs(asteroids[i])) { st.pop(); } else { st.pop(); i++; } } } } int[] ans = new int[st.size()]; for (int j = ans.length - 1; j >= 0; j--) { ans[j] = st.pop(); } return ans; } public static void main(String[] args) { int[] ques = { -2, -1, 1, 2 }; int[] ans = asteroidCollision(ques); for (int i = 0; i < ans.length; i++) System.out.print(ans[i] + ", "); System.out.println(); }}
- Assistant