[Leetcode 1046] 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

解题思路

题目要求每次取出当前石头堆中最大的两个,若它们相同,则直接销毁,若不同,则将一块重量等于它们差值的石头放入堆中。如此反复,直到最后至多只有一块石头。返回这块石头的重量,如果没有石头,返回0

既然每次都要取出最大的两个数,我们自然想到利用最大堆来维护数据。现将所有石头放入最大堆中,然后每次取出堆顶两个数进行操作。直到堆的规模小于等于1。如果等于1,返回堆顶元素,否则返回0

示例代码 (cpp)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
priority_queue<int> pq;
for (auto& stone : stones) {
pq.push(stone);
}
while (pq.size() >= 2) {
int t1 = pq.top();
pq.pop();
int t2 = pq.top();
pq.pop();
if (t1 != t2) {
pq.push(t1 - t2);
}
}
if (pq.empty()) {
return 0;
}
return pq.top();
}
};

示例代码 (java)

1
2
3
4
5
6
7
8
9
10
class Solution {
public int lastStoneWeight(int[] stones) {
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b)-> b - a);
for (int a : stones)
pq.offer(a);
while (pq.size() > 1)
pq.offer(pq.poll() - pq.poll());
return pq.poll();
}
}

示例代码 (python)

1
2
3
4
5
6
7
class Solution:
def lastStoneWeight(self, stones):
h = [-x for x in stones]
heapq.heapify(h)
while len(h) > 1 and h[0] != 0:
heapq.heappush(h, heapq.heappop(h) - heapq.heappop(h))
return -h[0]

复杂度分析

时间复杂度: 假设一共有N数,建立堆后,每次取出两个数,加入一个数,直到堆得规模小于等于1。一共有2N次删除和N次加入。每次删除时间复杂度是O(logN), 每次加入是O(1)。所有总的时间复杂度是O(NlogN)
空间复杂度: O(N)

归纳总结

我们在Youtube上更新了视频讲解,欢迎关注!

------ 关注公众号:猩猩的乐园 ------