当前位置:网站首页>2022.07.13 _ a day
2022.07.13 _ a day
2022-07-31 07:40:00 【No. い】
735. 行星碰撞
题目描述
给定一个整数数组 asteroids,表示在同一行的行星.
对于数组中的每一个元素,其绝对值表示行星的大小,正负表示行星的移动方向(正表示向右移动,负表示向左移动).每一颗行星以相同的速度移动.
找出碰撞后剩下的所有行星.碰撞规则:两个行星相互碰撞,较小的行星会爆炸.如果两颗行星大小相同,则两颗行星都会爆炸.两颗移动方向相同的行星,永远不会发生碰撞.
示例 1:
输入:asteroids = [5,10,-5]
输出:[5,10]
解释:10 和 -5 碰撞后只剩下 10 . 5 和 10 永远不会发生碰撞.
示例 2:
输入:asteroids = [8,-8]
输出:[]
解释:8 和 -8 碰撞后,两者都发生爆炸.
示例 3:
输入:asteroids = [10,2,-5]
输出:[10]
解释:2 和 -5 发生碰撞后剩下 -5 .10 和 -5 发生碰撞后剩下 10 .
提示:
2 <= asteroids.length <= 104-1000 <= asteroids[i] <= 1000asteroids[i] != 0
- 栈
- 数组
coding
// 栈模拟
class Solution {
public int[] asteroidCollision(int[] asteroids) {
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < asteroids.length; i++) {
if (stack.isEmpty() || stack.peek() * asteroids[i] > 0 || stack.peek() < 0) {
// 1.栈为空
// 2.The planet at the top of the stack moves in the same direction as the next planet
// 3.The planet at the top of the stack moves to the left (Even if the movement is oriented differently,This is equivalent to left facing left,right to right,不会发生碰撞)
stack.push(asteroids[i]);
} else {
// When two stars move towards each other,If the right-facing planet in the stack has a higher velocity,Then the new star explodes directly,Then look at the situation of the next planet
// 否则,Planets in the stack must explode
if (stack.peek() <= - asteroids[i]) {
// If the speed of the top planet is small,The newly added planets are still considered
if (stack.peek() < - asteroids[i]) {
i --;
}
// If the speed is the same, the planet at the top of the stack and the planet that needs to be added will die together
stack.pop();
}
}
}
int[] res = new int[stack.size()];
for (int i = res.length - 1; i >= 0; i--) {
res[i] = stack.pop();
}
return res;
}
}
边栏推荐
猜你喜欢
随机推荐
2. (1) Chained storage of stack, operation of chain stack (illustration, comment, code)
Financial leasing business
shell之条件语句(test、if、case)
DAY18:XSS 漏洞
SCI写作指南
任务及任务切换
自动翻译软件-批量批量自动翻译软件推荐
批量翻译软件免费【2022最新版】
事务的四大特性
2022.07.22_每日一题
Jobject 使用
Moment.js common methods
【解决】npm ERR A complete log of this run can be found in npm ERR
【Go语言入门教程】Go语言简介
【Star项目】小帽飞机大战(八)
Automatic translation software - batch batch automatic translation software recommendation
interrupt and pendSV
codec2 BlockPool:unreadable libraries
链表实现及任务调度
Obtaining server and client information








