美文网首页LeetCodeSwift in LeetCode高薪算法+计算机职称考试
LeetCode 1046. 最后一块石头的重量 Last St

LeetCode 1046. 最后一块石头的重量 Last St

作者: 1江春水 | 来源:发表于2019-08-26 18:09 被阅读0次

【题目描述】
有一堆石头,每块石头的重量都是正整数。

每一回合,从中选出两块最重的石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下:

  • 如果 x == y,那么两块石头都会被完全粉碎;
  • 如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x。
    最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0。
1、1 <= stones.length <= 30
2、1 <= stones[i] <= 1000

【思路】
1、排序
2、按道理来讲排序的复杂度高,但貌似耗时不多
3、时间复杂度O(nlogn)
4、空间复杂度O(1)

Swift代码实现:

func lastStoneWeight(_ stones: [Int]) -> Int {
    if stones.count == 1 {
        return stones[0]
    }
    var tmp = stones.sorted()
    while tmp.count > 0 {
        let maxFir = tmp.removeLast()
        let maxSec = tmp[tmp.count-1]
        let cha = maxFir-maxSec
        if cha == 0 {
            tmp.removeLast()
        } else {
            tmp[tmp.count-1] = cha
            tmp.sort()
        }
        if tmp.count == 0 {
            return 0
        }
        if tmp.count == 1 {
            return tmp.first!
        }
    }
    return 0
}

相关文章

网友评论

    本文标题:LeetCode 1046. 最后一块石头的重量 Last St

    本文链接:https://www.haomeiwen.com/subject/zqbdectx.html