当前位置:网站首页>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;
}
}
边栏推荐
- 从 Google 离职,前Go 语言负责人跳槽小公司
- 2022.7.29 数组
- 科普 | “大姨太”ETH 和 “小姨太”ETC的爱恨情仇
- 数据库概论 - MySQL的简单介绍
- 那些破釜沉舟入局Web3.0的互联网精英都怎么样了?
- 【微服务】 微服务学习笔记二:Eureka注册中心的介绍及搭建
- Log4net 思维导图
- 【C语言项目合集】这十个入门必备练手项目,让C语言对你来说不再难学!
- 讲解实例+详细介绍@Resource与@Autowired注解的区别(全网最全)
- Postgresql source code learning (33) - transaction log ⑨ - see the overall process of log writing from the insert record
猜你喜欢

Automatic translation software - batch batch automatic translation software recommendation

批量免费文字翻译

Project exercise - memorandum (add, delete, modify, check)

Zotero | Zotero translator插件更新 | 解决百度学术文献无法获取问题

360 push-360 push tool-360 batch push tool

文件 - 04 下载文件: 根据文件下载链接下载文件

DirectExchange switch simple introduction demo

PCB抄板

MySql的安装配置超详细教程与简单的建库建表方法

Explain the example + detail the difference between @Resource and @Autowired annotations (the most complete in the entire network)
随机推荐
强化学习科研知识必备(数据库、期刊、会议、牛人)
Difficulty comparison between high concurrency and multithreading (easy to confuse)
Run the NPM will pop up to ask "how are you going to open this file?"
把 VS Code 当游戏机
一文读懂 MongoDB 和 MySQL 的差异
【面试:并发篇37:多线程:线程池】自定义线程池
小实战项目之——吃货联盟订餐系统
拓扑排序的两种方法 --- dfs+Kahn
【第四章】详解Feign的实现原理
Automatic translation software - batch batch automatic translation software recommendation
tidyverse笔记——tidyr包
【C语言项目合集】这十个入门必备练手项目,让C语言对你来说不再难学!
测试 思维导图
文件 - 03 下载文件:根据文件id获取下载链接
SCI写作指南
文件 - 02 上传文件:上传临时文件到服务器
360 push-360 push tool-360 batch push tool
Kubernetes调度
讲解实例+详细介绍@Resource与@Autowired注解的区别(全网最全)
基于交替迭代法的交直流混合系统潮流计算matlab程序iEEE9节点系统算例