11package com .fishercoder .solutions ;
22
3- import java .util .Stack ;
3+ import java .util .Deque ;
4+ import java .util .LinkedList ;
45
56public class _735 {
67 public static class Solution1 {
78 public int [] asteroidCollision (int [] asteroids ) {
8- Stack <Integer > stack = new Stack ();
9+ Deque <Integer > stack = new LinkedList <> ();
910 for (int i = 0 ; i < asteroids .length ; i ++) {
1011 if (!stack .isEmpty () && stack .peek () > 0 && asteroids [i ] < 0 ) {
1112 if (Math .abs (stack .peek ()) < Math .abs (asteroids [i ])) {
@@ -27,7 +28,7 @@ public int[] asteroidCollision(int[] asteroids) {
2728 return result ;
2829 }
2930
30- private void collide (Stack <Integer > stack ) {
31+ private void collide (Deque <Integer > stack ) {
3132 do {
3233 Integer top = stack .pop ();
3334 if (!stack .isEmpty () && stack .peek () * top < 0 ) {
@@ -47,4 +48,43 @@ private void collide(Stack<Integer> stack) {
4748 } while (!stack .isEmpty ());
4849 }
4950 }
51+
52+ public static class Solution2 {
53+ /**
54+ * My completely original solution on 11/5/2021.
55+ */
56+ public int [] asteroidCollision (int [] asteroids ) {
57+ Deque <Integer > stack = new LinkedList <>();
58+ for (int a : asteroids ) {
59+ if (a > 0 ) {
60+ stack .addLast (a );
61+ } else {
62+ if (!stack .isEmpty () && stack .peekLast () > 0 ) {
63+ if (stack .peekLast () > Math .abs (a )) {
64+ continue ;
65+ } else if (stack .peekLast () == Math .abs (a )) {
66+ stack .pollLast ();
67+ } else {
68+ while (!stack .isEmpty () && stack .peekLast () > 0 && stack .peekLast () < Math .abs (a )) {
69+ stack .pollLast ();
70+ }
71+ if (!stack .isEmpty () && stack .peekLast () > 0 && stack .peekLast () == Math .abs (a )) {
72+ stack .pollLast ();
73+ continue ;
74+ } else if (stack .isEmpty () || stack .peekLast () < 0 ) {
75+ stack .addLast (a );
76+ }
77+ }
78+ } else {
79+ stack .addLast (a );
80+ }
81+ }
82+ }
83+ int [] ans = new int [stack .size ()];
84+ for (int i = stack .size () - 1 ; i >= 0 ; i --) {
85+ ans [i ] = stack .pollLast ();
86+ }
87+ return ans ;
88+ }
89+ }
5090}
0 commit comments