# 【LeetCode】 1046. Last Stone Weight
## Description
> 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.)
> Note:
1 <= stones.length <= 30
1 <= stones[i] <= 1000
> 我們有一堆石頭,每顆石頭都有一個正整數代表它的重量。
> 每一回合,我們選兩顆最大的石頭並讓它們相撞。假設那兩顆石頭的重量分別為x和y且x <= y,那麼相撞後的結果會是:
> 如果x == y,兩顆石頭都完全粉碎。
> 如果x != y,重量為x的石頭會完全粉碎,而重量為y的石頭重量會改為y - x。
> 最後只剩下一顆石頭時,回傳那顆石頭的重量(如果沒有剩下石頭就回傳0)。
> 提示:
1 <= stones.length <= 30
1 <= stones[i] <= 1000
## Example:
```
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.
```
## Solution
* 作法很直覺,找到最大的兩顆,相撞,直到剩一顆。
* 找最大的兩顆可以跑一次迴圈就完成,也可以用排序來找。
* 使用排序可以確保最大的一定在最前面兩個,但因為相撞完之後都要再排序一次,因此超級慢。
* 比較快的方法是直接找最大值和次大值,C++裡面有max_element可以使用。
---
- 有看到該題目有提到可以用heap,感覺也是很聰明的方法,不過這邊就沒有做了。
### Code
* 版本一
```C++=1
class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
while(stones.size() > 1)
{
sort(stones.rbegin(), stones.rend());
stones.push_back(abs(stones[0] - stones[1]));
stones.erase(stones.begin(), stones.begin() + 2);
}
if(stones.empty())
return 0;
return stones[0];
}
};
```
* 版本二
```C++=1
class Solution {
public:
int lastStoneWeight(vector<int>& stones) {
while(stones.size() > 1)
{
auto it1 = max_element(stones.begin(), stones.end());
int r = *it1;
stones.erase(it1);
auto it2 = max_element(stones.begin(), stones.end());
r -= *it2;
stones.erase(it2);
stones.push_back(r);
}
if(stones.empty())
return 0;
return stones[0];
}
};
```
###### tags: `LeetCode` `C++`