LeetCode 30 days Challenge - Day 12
本系列將對LeetCode新推出的30天算法挑戰進行總結記錄,旨在記錄學習成果、方便未來查閱,同時望爲廣大網友提供幫助。
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 weightx
is totally destroyed, and the stone of weighty
has new weighty-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 <= stones.length <= 30
1 <= stones[i] <= 1000
Solution
題目要求分析:給定一個整形數組,每個值代表一顆石子的質量。每次選取質量最大的兩顆石子(如果存在至少兩顆石子),若兩顆石子質量相等,則進行下一次選取;否則,將一顆質量爲它們的質量差的石子加入數組中。
解法:
簡單進行模擬,重點注意每次需要選取質量最大的兩顆,而且新加入石子後影響原有順序,考慮使用大頂堆進行存儲,作者採用的是STL中大頂堆實現的優先隊列<priority_queue>
。
確定了儲存結構,模擬操作如下:
- 首先遍歷數組,將“石子”加入優先隊列。
- 根據題目要求,當剩餘石子爲1顆或0顆時,結束循環,否則:
- 取隊首元素,賦值給y,並將之出隊;
- 再次取隊首元素,賦值給x,並將之出隊;
- 由於是優先隊列,y >= x,因此只需比較x是否與y相等:
- 相等:不進行操作,相當於兩顆石子抵消了。
- 不相等:將質量差值y-x加入優先隊列。
- 最後判斷隊列是否爲空即可,
int lastStoneWeight(vector<int>& stones) {
priority_queue<int> pq;
for (int i : stones) pq.push(i);
while (pq.size() > 1) {
int y = pq.top(); pq.pop();
int x = pq.top(); pq.pop();
if (x != y) pq.push(y - x);
}
return pq.empty() ? 0 : pq.top();
}
2020/4 Karl