题目地址:
https://leetcode.com/problems/last-stone-weight/
给定一个数组,每次取出两个最大的数 x x x和 y y y,如果 x ≠ y x\ne y x=y,则变为 ∣ x − y ∣ |x-y| ∣x−y∣放回数组,否则取出消失。重复此操作。问数组最后剩下哪个数(如果不剩则返回 0 0 0)。
可以用最大堆。代码如下:
class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
priority_queue<int> heap(stones.begin(), stones.end());
while (heap.size() > 1) {
int x = heap.top(); heap.pop();
int y = heap.top(); heap.pop();
if (x - y) heap.push(x - y);
}
return heap.size() ? heap.top() : 0;
}
};
时间复杂度 O ( n log n ) O(n\log n) O(nlogn), n n n是数组长度,空间 O ( n ) O(n) O(n)。