LeetCode 30天挑战 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:

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. 最后判断队列是否为空即可,

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

2020/4 Karl

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值