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