Re: [閒聊] 每日leetcode

作者: dont   2024-07-13 12:15:10
2751. Robot Collisions
## 思路
Sort by position
maintain一個往右走的stack (to_right)
如果遇到往左走的就比較大小, 照三種情形更新healths
最後回傳所有 >0 的health
## Complexity
Time Complexity: O(N logN) # sort, 用counting sort O(N)
Space Complexity: O(N) # stack
## Code
```python
class Solution:
def survivedRobotsHealths(self, positions: List[int], healths: List[int],
directions: str) -> List[int]:
n = len(positions)
heap = []
for idx, (pos, d) in enumerate(zip(positions, directions)):
heapq.heappush(heap, (pos, d, idx))
to_right = []
while heap:
pos, d, idx = heapq.heappop(heap)
if d == 'R':
to_right.append(idx)
continue
while to_right and healths[idx]:
if healths[to_right[-1]] > healths[idx]:
healths[to_right[-1]] -= 1
healths[idx] = 0
break
elif healths[to_right[-1]] == healths[idx]:
healths[idx] = healths[to_right.pop()] = 0
else:
healths[idx] -= 1
healths[to_right.pop()] = 0
return [health for health in healths if health]
```
太習慣直接用heap..
改用indices.sort直接快200ms:
indices = list(range(n))
indices.sort(key=lambda x: positions[x])
for idx in indices:
作者: oin1104 (是oin的說)   2024-07-13 12:16:00
你好 新版友 請發錢
作者: steven183 (steven183183)   2024-07-13 12:16:00
作者: DJYOMIYAHINA (通通打死)   2024-07-13 12:16:00
大師 錢
作者: dont   2024-07-13 12:17:00
不是應該反過來給我錢嗎QQ
作者: zizc06719 (毛哥)   2024-07-13 12:18:00
看來你不懂邊板 錢
作者: sustainer123 (caster)   2024-07-13 12:20:00
大師
作者: NCKUEECS (小惠我婆)   2024-07-13 12:20:00
作者: mushrimp5466 (吃了蝦子的蘑菇)   2024-07-13 12:26:00
大師
作者: Lilchicken (小雞 )   2024-07-13 12:28:00
外來種 錢

Links booklink

Contact Us: admin [ a t ] ucptt.com