当前位置:网站首页>leetcode-每日一题735. 行星碰撞(栈模拟)
leetcode-每日一题735. 行星碰撞(栈模拟)
2022-07-31 05:10:00 【lin钟一】

题目链接:https://leetcode.cn/problems/asteroid-collision/
思路
方法一、栈模拟
直接想法
用栈 st 来模拟行星碰撞,遍历 asteroids 数组,对于数组中的每一个元素,其绝对值表示行星的大小,正负表示行星的移动方向,所以只有 st 的栈顶为正,当前 asteroids[i] 元素为负才会发生碰撞,且会一直取出栈顶元素为正的行星比较,直到比他小的正的行星碰完或者为同负的行星才结束
算法
- 从左往右遍历行星数组 asteroids
- 使用变量 alive 记录行星 aster 是否还存在(即未发生爆炸)
- 当 aster < 0 (行星方向向左) && alive == true(行星 aster 是否还存在) && len(st) > 0(栈st不为空) && st[len(st)-1] > 0((行星方向向右))
1)如果栈顶元素大于等于 −aster,则行星 aster 发生爆炸,将 alive 置为false
2)如果栈顶元素小于等于 −aster,则栈顶元素表示的行星发生爆炸,执行出栈操作
3)重复以上判断直到不满足条件,如果最后 alive 为真,说明行星 aster 不会爆炸,则将 aster 入栈
代码示例
func asteroidCollision(asteroids []int) (st []int) {
for _, aster := range asteroids{
alive := true
for alive && len(st) > 0 && aster < 0 && st[len(st) - 1] > 0{
alive = st[len(st)-1] < -aster // aster 是否存在
if st[len(st)-1] <= -aster {
// 栈顶行星爆炸
st = st[:len(st)-1]
}
}
if alive{
st = append(st, aster)
}
}
return
}

复杂度分析
时间复杂度:O(n),其中 n 为数组 asteroids 的大小。遍历数组 asteroids 总共需要O(n)的时间。
空间复杂度:O(1)。不需要申请额外的空间。
边栏推荐
- 数据库上机实验1 数据库定义语言
- 联盟链的真实场景在哪里
- Flink sink redis 写入Redis
- Interviewer: If the order is not paid within 30 minutes, it will be automatically canceled. How to do this?
- 踏上编程之路,你必须要干的几件事
- C语言实验一 熟悉C程序的环境
- Refinement of the four major collection frameworks: Summary of List core knowledge
- The interviewer asked me TCP three handshake and four wave, I really
- 【LeetCode-SQL每日一练】——2. 第二高的薪水
- Simple command of mysql
猜你喜欢

Flask-based three-party login process

详解扫雷游戏(C语言)

10 【组件编码流程 组件自定义事件 全局事件总线】

MySQL (updating)

Interviewer, don't ask me to shake hands three times and wave four times again

C语言实验五 循环结构程序设计(二)

The interviewer asked me TCP three handshake and four wave, I really

剑指offer专项突击版 ---- 第 6 天
uni-app进阶之模版语法与数据绑定【day7】

08 【生命周期 组件】
随机推荐
uni-app进阶之自定义【day13】
【C语言3个基本结构详解——顺序、选择、循环】
MySQL (updating)
Redis Advanced - Cache Issues: Consistency, Penetration, Penetration, Avalanche, Pollution, etc.
Three handshakes and four waves
Linux系统安装mysql(rpm方式安装)
目标检测学习笔记
可以“繁殖”的程序
Sword Point Offer Special Assault Edition ---- Day 1
let和const命令
【JS面试题】面试官:“[1,2,3].map(parseInt)“ 输出结果是什么?答上来就算你通过面试
C语言实验一 熟悉C程序的环境
闭包(五)----一个常见的循环
MySQL-Explain详解
MySQL8.0.26安装配置教程(windows 64位)
【mysql 提高查询效率】Mysql 数据库查询好慢问题解决
03 【数据代理 事件处理】
闭包(二)
uni-app进阶之模版语法与数据绑定【day7】
mysql5.7.35安装配置教程【超级详细安装教程】