当前位置:网站首页>2022.07.13_每日一题
2022.07.13_每日一题
2022-07-31 06:07:00 【诺.い】
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.栈顶行星和下一个行星运动方向相同
// 3.栈顶行星朝左运动 (即使运动朝向不同,此时相当于左边朝左,右边朝右,不会发生碰撞)
stack.push(asteroids[i]);
} else {
// 两星相向而行的情况下,如果栈中朝右的行星速度大,则新进行星直接爆炸,接着看下一个行星的情况即可
// 否则,栈中行星必定爆炸
if (stack.peek() <= - asteroids[i]) {
// 如果栈顶行星速度小,则依旧考虑新加的行星
if (stack.peek() < - asteroids[i]) {
i --;
}
// 速度相等则栈顶行星和需要新加的行星同归于尽
stack.pop();
}
}
}
int[] res = new int[stack.size()];
for (int i = res.length - 1; i >= 0; i--) {
res[i] = stack.pop();
}
return res;
}
}
边栏推荐
猜你喜欢

数据库概论 - MySQL的简单介绍

Core Tower Electronics won the championship in the Wuhu Division of the 11th China Innovation and Entrepreneurship Competition
![[PSQL] SQL基础教程读书笔记(Chapter1-4)](/img/76/d416f79b7f2c93c1c79a285c30d3e6.png)
[PSQL] SQL基础教程读书笔记(Chapter1-4)

【Go语言入门】一文搞懂Go语言的最新依赖管理:go mod的使用

浅层了解欧拉函数

Bulk free text translation

【Go】Go 语言切片(Slice)

Install and use uView

Explain the example + detail the difference between @Resource and @Autowired annotations (the most complete in the entire network)

剑指offer(一)
随机推荐
Kubernetes scheduling
Automatic translation software - batch batch automatic translation software recommendation
leetcode 406. Queue Reconstruction by Height
线程中断方法
2. (1) Chained storage of stack, operation of chain stack (illustration, comment, code)
Zabbix6.2惊喜发布!特别优化中大型环境部署的性能!
线程唤醒机制
mysql的下载及安装使用
Zero-Shot Learning & Domain-aware Visual Bias Eliminating for Generalized Zero-Shot Learning
Third-party library-store
电压源的电路分析知识分享
单点登录 思维导图
2022.7.29 Array
4-1-7 二叉树及其遍历 家谱处理 (30 分)
2022.7.29 数组
SQLite数据库连接字符串
Zotero | Zotero translator plugin update | Solve the problem that Baidu academic literature cannot be obtained
2022.07.26_每日一题
360推送-360推送工具-360批量推送工具
【面试:并发篇37:多线程:线程池】自定义线程池