LeetCode 735. Asteroid Collision
Posted Dylan_Java_NYC
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 735. Asteroid Collision相关的知识,希望对你有一定的参考价值。
原题链接在这里:https://leetcode.com/problems/asteroid-collision/
题目:
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.
Example 1:
Input: asteroids = [5, 10, -5] Output: [5, 10] Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
Example 2:
Input: asteroids = [8, -8] Output: [] Explanation: The 8 and -8 collide exploding each other.
Example 3:
Input: asteroids = [10, 2, -5] Output: [10] Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
Example 4:
Input: asteroids = [-2, -1, 1, 2] Output: [-2, -1, 1, 2] Explanation: The -2 and -1 are moving left, while the 1 and 2 are moving right. Asteroids moving the same direction never meet, so no asteroids will meet each other.
Note:
- The length of
asteroids
will be at most10000
. - Each asteroid will be a non-zero integer in the range
[-1000, 1000].
.
题解:
Have a queue, when it is positive number ,add to the back.
When it is negative, poll from the last if last number is positive but smaller than -num.
If queue is empty or last number is negative, then add num.
Else if last number == -num, poll it out.
The nums in queue is the result.
Time Complexity: O(n). n = asteroids.length.
Space: O(n).
AC Java:
1 class Solution { 2 public int[] asteroidCollision(int[] asteroids) { 3 if(asteroids == null || asteroids.length == 0){ 4 return asteroids; 5 } 6 7 LinkedList<Integer> que = new LinkedList<>(); 8 for(int num : asteroids){ 9 if(num > 0){ 10 que.add(num); 11 }else if(num < 0){ 12 while(!que.isEmpty() && que.peekLast() > 0 && que.peekLast() < -num){ 13 que.pollLast(); 14 } 15 16 if(que.isEmpty() || que.peekLast() < 0){ 17 que.add(num); 18 }else if(que.peekLast() == -num){ 19 que.pollLast(); 20 } 21 } 22 } 23 24 int [] arr = new int[que.size()]; 25 for(int i = 0; i < arr.length; i++){ 26 arr[i] = que.pollFirst(); 27 } 28 29 return arr; 30 } 31 }
以上是关于LeetCode 735. Asteroid Collision的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 735. Asteroid Collision
[LeetCode] Asteroid Collision 行星碰撞