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

  • 相关阅读:
    Ajax基础1
    jQuery框架源码解读
    关于struts、spring 和 hibernate的说明
    struts2学习笔记(一)
    NodeJS+MongoDB
    最佳实践(二)
    ajax请求web容器控制超时
    实战经验
    javascript学习笔记(二)
    spring学习笔记(六)
  • 原文地址:https://www.cnblogs.com/dreamtaker/p/14671010.html
Copyright © 2011-2022 走看看