Re: [闲聊] 每日leetcode

楼主: JIWP (JIWP)   2024-07-13 12:44:06
看到hard原本以为完了
不过之前就写过了
重写一次就好,有点卡就是了
2751. Robot Collisions
给你一堆机器人,每个机器人都有以下资讯
[position,health,direction]
每个机器人都在同一条路上,当两台机器人在路上碰到时
health比较小的就会爆炸,剩下的那台health会减一
请把最后剩下的机器人health列出来
并球按照原本的顺序
思路:
将每台机器direction、原本的index按照positionu由小排到大
接着就让机器人开始碰撞,并且用stack纪录往右边走的机器人
会有3种情况
(1)机器人往右走,丢到stack里
(2)机器人往左走,如果stack里面没有其他机器人,就不要理他
(3)机器人往左走,让他跟stack里的机器人碰撞,一直到他的health==0或是stack里没有其他机器人
最后找出health!=的机器人就好
golang code :
type Robot struct {
pos int
direct byte
idx int
}
func survivedRobotsHealths(positions []int, healths []int, directions string)
[]int {
n := len(healths)
robot := make([]Robot, len(healths))
for i := 0; i < n; i++ {
robot[i] = Robot{positions[i], directions[i], i}
}
slices.SortFunc(robot, func(i, j Robot) int {
return i.pos - j.pos
})
stack := make([]int, 0)
for _, val := range robot {
if val.direct == 'R' {
stack = append(stack, val.idx)
} else {
for len(stack) != 0 && healths[val.idx] != 0 {
idx := len(stack) - 1
if healths[stack[idx]] > healths[val.idx] {
healths[val.idx] = 0
healths[stack[idx]] -= 1
continue
} else if healths[stack[idx]] == healths[val.idx] {
healths[val.idx] = 0
healths[stack[idx]] = 0
} else {
healths[stack[idx]] = 0
healths[val.idx] -= 1
}
stack = stack[:idx]
}
}
}
rec := make([]int, 0)
for _, val := range healths {
if val != 0 {
rec = append(rec, val)
}
}
return rec
}
作者: oin1104 (是oin的说)   2024-07-13 12:58:00
大师 送我模型

Links booklink

Contact Us: admin [ a t ] ucptt.com