leetcode 1046. 最后一块石头的重量(C++、python)

有一堆石头,每块石头的重量都是正整数。

每一回合,从中选出两块最重的石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下:

  • 如果 x == y,那么两块石头都会被完全粉碎;
  • 如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x

最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0

 

提示:

1 <= stones.length <= 30

1 <= stones[i] <= 1000

C++

class Solution {
public:
    int lastStoneWeight(vector<int>& stones) 
    {
        int n=stones.size();
        priority_queue<int> que;
        for(int i=0;i<n;i++)
        {
            que.push(stones[i]);
        }
        if(1==n)
        {
            return stones[0];
        }
        else
        {
            while(que.size()>1)
            {
                int s1=que.top();
                que.pop();
                int s2=que.top();
                que.pop();
                if(s1!=s2)
                {
                    int tmp=abs(s1-s2);
                    que.push(tmp);
                }
            }
            if(1==que.size())
            {
                return que.top();
            }
            else
            {
                return 0;
            }
        }
        
    }
};

python

import queue
class Solution:
    def lastStoneWeight(self, stones: List[int]) -> int:
        n=len(stones)
        que=queue.PriorityQueue()
        for i in stones:
            que.put(-i)
        if 1==n:
            return stones[0]
        else:
            while que.qsize()>1:
                a=que.get()
                b=que.get()
                if a!=b:
                    que.put(-abs(a-b))
            if 1==que.qsize():
                return -que.get()
            else:
                return 0

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值