1046. Last Stone Weight

題目
最直覺的作法就是先排序,取出最重的兩個撞擊後,把剩下的放回去,然後重複以上步驟:

Intuitive Python 3 solution
1
2
3
4
5
6
7
8
def lastStoneWeight(self, stones: List[int]) -> int:
while len(stones) > 1:
stones.sort()
s1 = stones.pop()
s2 = stones.pop()
if s1 != s2:
stones.append(s1 - s2)
return stones[0] if stones else 0

但這樣的時間複雜度為 O(n^2 * log n),太大了,有沒有其他方法?

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×