0%

leetcode-day-12

LeetCode 30 days Challenge - Day 12

本系列将对LeetCode新推出的30天算法挑战进行总结记录,旨在记录学习成果、方便未来查阅,同时望为广大网友提供帮助。


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 weight x is totally destroyed, and the stone of weight y has new weight y-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:

1
2
3
4
5
6
7
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. 1 <= stones.length <= 30
  2. 1 <= stones[i] <= 1000

Solution

题目要求分析:给定一个整形数组,每个值代表一颗石子的质量。每次选取质量最大的两颗石子(如果存在至少两颗石子),若两颗石子质量相等,则进行下一次选取;否则,将一颗质量为它们的质量差的石子加入数组中。

解法:

简单进行模拟,重点注意每次需要选取质量最大的两颗,而且新加入石子后影响原有顺序,考虑使用大顶堆进行存储,作者采用的是STL中大顶堆实现的优先队列<priority_queue>

确定了储存结构,模拟操作如下:

  1. 首先遍历数组,将“石子”加入优先队列。
  2. 根据题目要求,当剩余石子为1颗或0颗时,结束循环,否则:
    1. 取队首元素,赋值给y,并将之出队;
    2. 再次取队首元素,赋值给x,并将之出队;
    3. 由于是优先队列,y >= x,因此只需比较x是否与y相等:
      1. 相等:不进行操作,相当于两颗石子抵消了。
      2. 不相等:将质量差值y-x加入优先队列。
  3. 最后判断队列是否为空即可,

1
2
3
4
5
6
7
8
9
10
int lastStoneWeight(vector<int>& stones) {
priority_queue<int> pq;
for (int i : stones) pq.push(i);
while (pq.size() > 1) {
int y = pq.top(); pq.pop();
int x = pq.top(); pq.pop();
if (x != y) pq.push(y - x);
}
return pq.empty() ? 0 : pq.top();
}

传送门:Last Stone Weight

Karl