zoukankan      html  css  js  c++  java
  • 【数据结构】最后一块石头的重量 Last Stone Weight

    Last Stone Weight 最后一块石头的重量

    We have a collection of stone , 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.)

    输入:[2,7,4,1,8,1]
    输出:1
    解释:
    先选出 7 和 8,得到 1,所以数组转换为 [2,4,1,1,1],
    再选出 2 和 4,得到 2,所以数组转换为 [2,1,1,1],
    接着是 2 和 1,得到 1,所以数组转换为 [1,1,1],
    最后选出 1 和 1,得到 0,最终数组转换为 [1],这就是最后剩下那块石头的重量。
     
    

    思路

    可以通过大顶堆,将所有数字入堆,每次poll,都是最大的。

    做差后大于0 ,就再入堆。

    public int lastStoneWeight(int[] stones) {
            PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>((o1,o2)->o2-o1);
            for (int stone : stones) {
                priorityQueue.offer(stone);
            }
            while (priorityQueue.size() >1) {
                int x = priorityQueue.poll();
                int y = priorityQueue.poll();
                if (x > y) {
                    priorityQueue.offer(x - y);
                }
            }
             
            return priorityQueue.isEmpty() ? 0 : priorityQueue.poll();
            
        }
    

    Tag

    heap

  • 相关阅读:
    网页布局——table布局
    Flex 布局——语法属性详解
    CSS实现垂直居中的几种方法
    svn:冲突(<<<<<<.mine ==== >>>>>>.xxxx)
    mysql:4种时间类型
    js:"use strict"; 严格模式
    js函数的Json写法
    spring 官方文档
    mybatis技术文章
    java:可变参数(转载)
  • 原文地址:https://www.cnblogs.com/dreamtaker/p/14671010.html
Copyright © 2011-2022 走看看