当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢
随机推荐
【第四章】详解Feign的实现原理
2022.07.13_每日一题
LeetCode刷题——摆动序列#376#Medium
剑指offer(一)
庐山谣寄卢侍御虚舟
One of the small practical projects - food alliance ordering system
我开发了一个利用 Bun 执行 .ts / .js 文件的 VS Code 插件
SCI写作指南
Install the gstreamer development dependency library to the project sysroot directory
2022.07.20_每日一题
双倍数据速率同步动态随机存储器(Double Data Rate Synchronous Dynamic Random Access Memory, DDR SDRAM)- 逻辑描述部分
Difficulty comparison between high concurrency and multithreading (easy to confuse)
零样本学习&Domain-aware Visual Bias Eliminating for Generalized Zero-Shot Learning
2022.07.26_每日一题
03-SDRAM: Write operation (burst)
2022.7.29 数组
Jobject 使用
360推送-360推送工具-360批量推送工具
文件 - 04 下载文件: 根据文件下载链接下载文件
bcos简介及自序



![[PSQL] SQL基础教程读书笔记(Chapter1-4)](/img/76/d416f79b7f2c93c1c79a285c30d3e6.png)





