[Java][LeetCode][Stack]Asteroid Collision #735

SP Hou
Apr 27, 2022

--

行星碰撞條件是:
1. 兩個行星要不同的方向
2. 行星是依序碰撞的,不會跳著碰撞
3. 小的行星會被撞毀,一樣大小的時候會兩個都撞毀
4. 後者往前看要撞擊的行星,如果被撞掉了,就再繼續往前比較
5. 當前者為負的,後者為正的,不會被撞掉
因為要一直往前追著碰撞,所以用stack去存放前面的行星。當現在的行星的絕對值小於stack棧頂的絕對值,則表示當下的行星會被撞毀,當現在的行星的絕對值等於棧頂的絕對值,表示兩個都會被撞毀。當現在的行星的絕對值大於棧頂的絕對值,表示棧內的會被一直追朔到棧頂的行星與當下行星方向相同、棧被撞光了或是棧頂比當前行星還要大才會停下來。直到歷遍全部的行星。最後,將棧內剩下的全部倒到array中輸出。

Asteroids collision conditions are:
1. They are in different directions.
2. Asteroids collide in order in the sequence.
3. The small one will explode. The same size will explode with each other.
4. back one collides front one, if the front is explode, the back one will collide continuously. Until all ahead asteroids explode.
5. When the front one is negative, and the back one is positive, they won’t collide.
with the mention above, I got those conditions:
current<top of the stack: current will collide. The current asteroids will not be kept.
current = top: current and top will collide. the top one will be removed from the stack.
current>top: collide continuously.

--

--