Asteroid Collision (M)
題目
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.
Constraints:
1 <= asteroids <= 10^4-1000 <= asteroids[i] <= 1000asteroids[i] != 0
題意
給定一個包含正數和負數的陣列,正數代表會向右跑的行星,負數代表會向左的跑的行星,當兩行星相遇,大尺寸的行星會撞碎小尺寸的,相同尺寸的都碎,問陣列最后剩下的值,
思路
用堆疊實作:從左到右遍歷,如果堆疊慷訓者是正數,則壓入堆疊(正數只會向右跑,不會與已在堆疊中的發生碰撞);如果是負數,與堆疊頂比較,按情況判斷: 1. 堆疊頂也是負數;2. 絕對值比堆疊頂大;3. 絕對值比堆疊頂小;4. 絕對值和堆疊頂相同;5. 堆疊空,
代碼實作
Java
class Solution {
public int[] asteroidCollision(int[] asteroids) {
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < asteroids.length; i++) {
int cur = asteroids[i];
if (stack.isEmpty() || cur > 0) {
stack.push(cur);
} else {
boolean flag = true;
while (!stack.isEmpty() && stack.peek() > 0 && -cur >= stack.peek()) {
if (-cur == stack.peek()) {
stack.pop();
flag = false;
break;
}
stack.pop();
}
if (flag && (stack.isEmpty() || stack.peek() < 0)) {
stack.push(cur);
}
}
}
int[] ans = new int[stack.size()];
for (int i = stack.size() - 1; i >= 0; i--) {
ans[i] = stack.pop();
}
return ans;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/185466.html
標籤:其他
