博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
lc1046. Last Stone Weight
阅读量:6690 次
发布时间:2019-06-25

本文共 1571 字,大约阅读时间需要 5 分钟。

  1. Last Stone Weight Easy

83

8

Favorite

Share We have a collection of rocks, each rock has a positive integer weight.

Each turn, we choose the two heaviest rocks 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 <= stones.length <= 30 1 <= stones[i] <= 1000 思路:从大到小排序,然后比较头两个元素,如果一样大,就都删除,如果一个比另一个大,插入他们的差的绝对值,while循环,直到只有一个元素或没有

代码:python3

class Solution:    def lastStoneWeight(self, stones) -> int:        while len(stones) > 1:            stones.sort(reverse=True)            print(stones)            if stones[0]==stones[1]:                stones=stones[2:]            else:                num=abs(stones[0]-stones[1])                stones=stones[2:]                print(stones)                stones.insert(0,num)                # print(stones)        if len(stones)==1:            return stones[0]        else:            return 0复制代码

转载于:https://juejin.im/post/5d07771a51882559ef78eb27

你可能感兴趣的文章
Visual Paradigm 教程[企业架构]:如何绘制ArchiMate图?
查看>>
Git 提交的正确姿势:Commit message 编写指南
查看>>
分享HTML5自动化构建工具gulp使用方法步骤
查看>>
PHP 包含文件
查看>>
BootStrap 资源汇总
查看>>
为Empathy增加QQ支持
查看>>
Caused by: java.lang.IllegalArgumentException: Service Intent must be explicit:
查看>>
rabbitmq的使用笔记
查看>>
QT临时笔记
查看>>
一次、二次、三次指数平滑计算思想及代码
查看>>
TIDB 最佳实践
查看>>
linux 中mysql命令使用
查看>>
如何在 Laravel 中 “规范” 的开发验证码发送功能【社交系统ThinkSNS研发日记十一】...
查看>>
Linux 安装JDK Tomcat Eclipse
查看>>
arp(中间人***)-为pe文件注入后门
查看>>
13.2管理网络冗余与数据存储群集
查看>>
阿里开源的 java 诊断工具—— Arthas
查看>>
dedecms广告功能分析
查看>>
Confluence 6 升级自定义的站点和空间获得你的自定义布局
查看>>
Angular CLI 创建你的第一个 Angular 示例程序
查看>>