Day12-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.)
这道题描述的应该就是数据结构中的大根堆的情况吧,每次从堆中拿出两个最大的相减,再放回堆中(0不放回去),直到堆中只有一个元素或者没有元素为止。
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.
解法一:
我们遍历这个数组中元素,每遍历一个元素之前先排序,然后排出两个最大的,再把最大的加进去,最后返回第一个元素就行了。
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
for i in range(len(stones) - 1):
stones.sort()
stones.append(stones.pop() - stones.pop())
return stones[0]
时间复杂度:这种就是纯暴力,时间复杂度高的多了,python的sort函数的时间复杂度为nlogn,然后还在循环里面应该就是O(n*nlogn).这解法也就一乐。还得看下面的大根堆的解法。
解法二:
用到了python的heap数据结构,但是python的是小根堆,为此我们先取反,然后再最后返回的时候加上负号就行了。
class Solution(object):
def lastStoneWeight(self, stones):
"""
:type stones: List[int]
:rtype: int
"""
stones = [-x for x in stones]
heapq.heapify(stones)
while len(stones) > 1:
x = heapq.heappop(stones)
if stones:
y = heapq.heappop(stones)
if x != y:
heapq.heappush(stones, -abs(x - y))
return 0 if not stones else -stones[0]
时间复杂度为O(nlogn).其实我觉得这两种做法都不太符合出题者的要求吧,出题者可能是要我们自己手动去实现一个大根堆的解法,而不是用python的内置函数来做。。。
有时间会再手写一个大根堆的解法。
本文介绍了一种算法问题,即如何通过一系列操作确定一组石头中最后一块石头的重量。使用了两种解法,一种是暴力排序法,另一种是利用Python的heap数据结构实现的大根堆解法,详细解释了每种方法的实现过程及时间复杂度。

被折叠的 条评论
为什么被折叠?



