150强访谈简单

最后一块石头的重量

“最后一块石头重量”问题的详细指南和 Python 实现。

问题陈述

简单

给定一个整数石头数组,其中stones[i] 是第 i 个石头的重量。

我们正在玩石头游戏。在每一轮中,我们选择最重的两块石头并将它们粉碎在一起。假设最重的两块石头的重量为 x 和 y,且 x <= y。这次粉碎的结果是:

- 如果 x == y,两块石头都会被摧毁,

- 如果 x != y,则重量 x 的石头被破坏,重量 y 的石头具有新的重量 y - x。

游戏结束时,最多还剩下一颗棋子。

返回最后剩下的石头的重量。如果没有剩下石子,则返回 0。

编写一个函数 lastStoneWeight(stones: List[int]) -> int

约束条件
  • 1 <= len(stones) <= 30
  • 1 <= stones[i] <= 1000

示例

Example 1
Input
stones = [2,7,4,1,8,1]
Output
1
Explanation

Smash 7 and 8 to get 1, array becomes [2,4,1,1,1]. Smash 2 and 4 to get 2, array becomes [2,1,1,1]. Smash 2 and 1 to get 1, array becomes [1,1,1]. Smash 1 and 1 to get 0, array becomes [1]. The last remaining stone is 1.

Example 2
Input
stones = [1]
Output
1
Explanation

Only one stone, so weight is 1.

Need a Hint?
考虑使用堆/优先级队列特定的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。