【Leetcode】735. Asteroid Collision
題目地址:
https://leetcode.com/problems/asteroid-collision/
給定一個不含 0 0 0的長 n n n陣列 A A A,表示一個數軸上的小行星的速度,正數代表向右,負數代表向左,絕對值代表小行星的質量。同向的小行星不會相撞,但反向的小行星會相撞,相撞的結果是,質量大的繼續存在,小的爆炸;如果質量一樣則都爆炸。問最後剩下的小行星的速度狀態是什麼,返回一個陣列。
其實就是模擬相撞的過程。開個棧,遍歷 A A A,如果遇到了向右的小行星則直接入棧;否則,如果棧空或者棧頂也是向左的小行星,則也入棧,如果棧不空並且棧頂是向右的小行星,則進行相撞操作,直到棧空或者棧頂是向左的小行星為止,同時記錄一下當前小行星是否爆炸。如果退出迴圈的時候當前小行星沒有爆炸,則入棧。最後逆序存一下棧,就是答案。程式碼如下:
import java.util.ArrayDeque;
import java.util.Deque;
public class Solution {
public int[] asteroidCollision(int[] asteroids) {
Deque<Integer> stack = new ArrayDeque<>();
for (int asteroid : asteroids) {
if (asteroid > 0) {
stack.push(asteroid);
} else {
if (stack.isEmpty() || stack.peek() < 0) {
stack.push(asteroid);
continue;
}
boolean exploded = false;
while (!stack.isEmpty() && stack.peek() > 0) {
if (stack.peek() > -asteroid) {
exploded = true;
break;
} else if (stack.peek() == -asteroid) {
exploded = true;
stack.pop();
break;
} else if (stack.peek() < -asteroid) {
stack.pop();
}
}
// 如果asteroid沒炸,則入棧
if (!exploded) {
stack.push(asteroid);
}
}
}
int[] res = new int[stack.size()];
int idx = 0;
while (!stack.isEmpty()) {
res[idx++] = stack.pop();
}
// 最後反個序
reverse(res);
return res;
}
private void reverse(int[] A) {
for (int i = 0, j = A.length - 1; i < j; i++, j--) {
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
}
}
時空複雜度 O ( n ) O(n) O(n)。
相關文章
- LeetCode 735. Asteroid Collision All In OneLeetCodeAST
- 如何用double hashing解決collision resolution問題
- 06 Coloured Petri Net-based Traffic Collision Avoidance System encounter model for the analysis of
- 密碼學系列之:碰撞抵禦和碰撞攻擊collision attack密碼學
- 【LeetCode】如何學習LeetCode?LeetCode
- leetcodeLeetCode
- LeetCode in actionLeetCode
- leetcode 238LeetCode
- LeetCode 164 最大間距 HERODING的LeetCode之路LeetCode
- LeetCode 143 重排連結串列 HERODING的LeetCode之路LeetCode
- LeetCode問題LeetCode
- 【LeetCode】Jewels and StonesLeetCode
- Leetcode 513 javascriptLeetCodeJavaScript
- LeetCode 162 JavascriptLeetCodeJavaScript
- Leetcode 921 JavascriptLeetCodeJavaScript
- [Leetcode] Edit DistanceLeetCode
- LeetCode 克隆圖LeetCode
- LeetCode #378 JavaScriptLeetCodeJavaScript
- LeetCode 747 JavaScriptLeetCodeJavaScript
- Leetcode725LeetCode
- LeetCode 53 JSLeetCodeJS
- LeetCode 50 JSLeetCodeJS
- Leetcode03LeetCode
- LeetCode 799 JavaScriptLeetCodeJavaScript
- leetcode690LeetCode
- [LeetCode] Group AnagramLeetCode
- [LeetCode] Rotate StringLeetCode
- LeetCode 283 jsLeetCodeJS
- Leetcode #463 JavascriptLeetCodeJavaScript
- Leetcode # 495 JavascriptLeetCodeJavaScript
- Leetcode 229 JavaScriptLeetCodeJavaScript
- golang刷leetcodeGolangLeetCode
- Leetcode目錄LeetCode
- LeetCode:快速排序LeetCode排序
- leetcode Sum系列LeetCode
- LeetCode三則LeetCode
- LeetCode2:LeetCode
- The best LeetCode NodesLeetCode