题目名称
- 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 就是比较的方式。当需要用自定义的数据类型时才需要传入这三个参数,使用基本数据类型时,只需要传入数据类型,默认是大顶堆。