当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢

讲解实例+详细介绍@Resource与@Autowired注解的区别(全网最全)

In-depth analysis of z-index

Automatic translation software - batch batch automatic translation software recommendation

【云原生】-Docker安装部署分布式数据库 OceanBase

Analysis of the implementation principle and detailed knowledge of v-model syntactic sugar and how to make the components you develop support v-model

Analysis of the principle and implementation of waterfall flow layout

拓扑排序的两种方法 --- dfs+Kahn

Conditional statements of shell (test, if, case)

简单谈谈Feign

解决安装 Bun 之后出现 zsh compinit: insecure directories, run compaudit for list. Ignore insecure directorie
随机推荐
【科普向】5G核心网架构和关键技术
2022.07.24_每日一题
CHI论文阅读(1)EmoGlass: an End-to-End AI-Enabled Wearable Platform for Enhancing Self-Awareness of Emoti
tidyverse笔记——tidyr包
【Go语言入门】一文搞懂Go语言的最新依赖管理:go mod的使用
那些破釜沉舟入局Web3.0的互联网精英都怎么样了?
codec2 BlockPool:不可读库
零样本学习&Domain-aware Visual Bias Eliminating for Generalized Zero-Shot Learning
二叉树的还原(反序列化)
DDL+DML+DQL
2022.7.29 数组
知识、创新、回报。
R——避免使用 col=0
MySQL系列一:账号管理与引擎
PCB抄板
【Go报错】go go.mod file not found in current directory or any parent directory 错误解决
【C语言项目合集】这十个入门必备练手项目,让C语言对你来说不再难学!
单点登录 思维导图
Obtaining server and client information
iOS大厂面试查漏补缺