当前位置:网站首页>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] <= 1000
asteroids[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;
}
}
边栏推荐
- tidyverse笔记——tidyr包
- 2. (1) Chained storage of stack, operation of chain stack (illustration, comment, code)
- Postgresql source code learning (33) - transaction log ⑨ - see the overall process of log writing from the insert record
- mysql的下载及安装使用
- 【微服务】 微服务学习笔记二:Eureka注册中心的介绍及搭建
- 拓扑排序的两种方法 --- dfs+Kahn
- Obtaining server and client information
- Database Principles Homework 3 — JMU
- Difficulty comparison between high concurrency and multithreading (easy to confuse)
- 【Go】Go 语言切片(Slice)
猜你喜欢
随机推荐
【Star项目】小帽飞机大战(八)
HighTec 的安装与配置
LeetCode刷题——摆动序列#376#Medium
Detailed explanation of js prototype
360 push-360 push tool-360 batch push tool
一文读懂 MongoDB 和 MySQL 的差异
postgresql源码学习(34)—— 事务日志⑩ - 全页写机制
【TA-霜狼_may-《百人计划》】美术2.3 硬表面基础
QFileInfo常规方法
把 VS Code 当游戏机
Zabbix6.2惊喜发布!特别优化中大型环境部署的性能!
How to choose a suitable UI component library in uni-app
《白帽子说Web安全》思维导图
基于交替迭代法的交直流混合系统潮流计算matlab程序iEEE9节点系统算例
【并发编程】ReentrantLock的lock()方法源码分析
Exam Questions Previous True Questions Wrong Bills [The Fourth Session] [Provincial Competition] [Group B]
Kubernetes调度
Zero-Shot Learning & Domain-aware Visual Bias Eliminating for Generalized Zero-Shot Learning
知识、创新、回报。
MySQL笔记下