[LeetCode] 1046. Last Stone Weight 最后的石头重量
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),或者剩下一个石头(返回该石头的重量)。这道题是一道 Easy 的题目,没有太大的难度,主要就是每次要选出最大的两个数字,若是给数组排序,是可以知道最后两个数字是最大的,然是碰撞过后若有剩余,要将这个剩余的石头加到数组的合适位置,每次都排一次序显然时间复杂度太大。这里需要用一个更合理的数据结构,最大堆,在 C++ 中用优先队列实现的,每次加入一个新的石头,就会自动根据其重量加入到正确的位置。起始时将所有的石头加入优先队列中,然后进行循环,条件是队列中的石头个数大于1,然后取出队首两个石头,假如重量不等,则将差值加入队列。最终只需要判断队列是否为空,是的话返回0,否则返回队首元素,参见代码如下:
class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
priority_queue<int> q;
for (int stone : stones) q.push(stone);
while (q.size() > 1) {
int first = q.top(); q.pop();
int second = q.top(); q.pop();
if (first > second) q.push(first - second);
}
return q.empty() ? 0 : q.top();
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/1046
参考资料:
https://leetcode.com/problems/last-stone-weight/
https://leetcode.com/problems/last-stone-weight/discuss/294956/JavaC%2B%2BPython-Priority-Queue