原题说明
We have a collection of stones, each stone has a positive integer weight.
Each turn, we choose the two heaviest stones and smash them together. Suppose the stones have weights x
and y
with x <= y
. The result of this smash is:
- If
x == y
, both stones are totally destroyed; - If
x != y
, the stone of weightx
is totally destroyed, and the stone of weighty
has new weighty-x
.
At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.)
Example 1:
Input: [2,7,4,1,8,1]
Output: 1
Explanation:
We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we combine 1 and 1 to get 0 so the array converts to [1] then that’s the value of last stone.
Note:
1 <= stones.length <= 30
1 <= stones[i] <= 1000
解题思路
题目要求每次取出当前石头堆中最大的两个,若它们相同,则直接销毁,若不同,则将一块重量等于它们差值的石头放入堆中。如此反复,直到最后至多只有一块石头。返回这块石头的重量,如果没有石头,返回0
。
既然每次都要取出最大的两个数,我们自然想到利用最大堆来维护数据。现将所有石头放入最大堆中,然后每次取出堆顶两个数进行操作。直到堆的规模小于等于1
。如果等于1
,返回堆顶元素,否则返回0
。
示例代码 (cpp)
1 | class Solution { |
示例代码 (java)
1 | class Solution { |
示例代码 (python)
1 | class Solution: |
复杂度分析
时间复杂度: 假设一共有N
数,建立堆后,每次取出两个数,加入一个数,直到堆得规模小于等于1
。一共有2N
次删除和N
次加入。每次删除时间复杂度是O(logN)
, 每次加入是O(1)
。所有总的时间复杂度是O(NlogN)
空间复杂度: O(N)
归纳总结
我们在Youtube上更新了视频讲解,欢迎关注!