Leetcode_C++笔记之1046. Last Stone Weight(最后一颗石头的权重)

题目名称

  1. Last Stone Weight

题目描述

ou are given an array of integers stones where stones[i] is the weight of the ith stone.

We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights x and y with x <= y. The result of this smash is:

If x == y, both stones are destroyed, and
If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x.
At the end of the game, there is at most one stone left.

Return the weight of the last remaining stone. If there are no stones left, return 0.

初试思路

1、按照题目依次找出两个最大值并将对应位置置零,然后这两个最大值相减,结果插入到数组中值是0的位置,最后如果第二个最大值是0,则返回第一个最大值。
2、优先队列(最大堆heap)

初试代码

// 我的代码1
class Solution {
public:
    int lastStoneWeight(vector<int>& stones) {
        int max1, max2;
        while(1){
            max1 = max(stones);
            max2 = max(stones);
            if(max2==0)
                return max1;
            insert(stones, max1-max2);
        }
        return 0;
    }
    int max(vector<int>& stones){
        int max_i = 0;
        int max = 0;
        for(int i=0; i<stones.size(); i++){
            if(stones[i] > stones[max_i]){
                max_i = i;
            }
        }
        max = stones[max_i];
        stones[max_i] = 0;
        return max;
    }
    void insert(vector<int> & stones, int value){
        for(int i=0; i<stones.size(); i++){
            if(stones[i]==0){
                stones[i] = value;
                return;
            }
        }
    }
};

// 我的代码2
class Solution {
public:
    int lastStoneWeight(vector<int>& stones) {
        priority_queue<int > pq(stones.begin(), stones.end());
        while(pq.size()>1){
            int max1 = pq.top();
            pq.pop();
            int max2 = pq.top();
            pq.pop();
            pq.push(max1-max2);
        }
        return pq.top();
    }
};

学到了啥

C++优先队列(priority_queue)
首先要包含头文件#include, 他和queue不同的就在于我们可以自定义其中数据的优先级, 让优先级高的排在队列前面,优先出队。优先队列具有队列的所有特性,包括队列的基本操作,只是在这基础上添加了内部的一个排序,它本质是一个堆实现的。

基本操作
它的基本操作和队列基本操作相同:
top 访问队头元素
empty 队列是否为空
size 返回队列内元素个数
push 插入元素到队尾 (并排序)
emplace 原地构造一个元素并插入队列
pop 弹出队头元素
swap 交换内容

基本使用
定义:priority_queue<Type, Container, Functional>
Type 就是数据类型,Container 就是容器类型(Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector),Functional 就是比较的方式。当需要用自定义的数据类型时才需要传入这三个参数,使用基本数据类型时,只需要传入数据类型,默认是大顶堆。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值