zoukankan      html  css  js  c++  java
  • 1046. 最后一块石头的重量

    有一堆石头,每块石头的重量都是正整数。

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

    • 如果 x == y,那么两块石头都会被完全粉碎;
    • 如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x

    最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0

    提示:

    1. 1 <= stones.length <= 30
    2. 1 <= stones[i] <= 1000

    题解:使用大根堆维护

    class Solution {
        public int lastStoneWeight(int[] stones) {
            PriorityQueue<Integer> heap = new PriorityQueue<>((o1,o2)->o2.compareTo(o1));
            for(int stone:stones){
                heap.offer(stone);
            }
            while(heap.size()>1){
                int s1 = heap.poll();
                int s2 = heap.poll();
                if(s1==s2) continue;
                int max = Math.max(s1,s2);
                int min = Math.min(s1,s2);
                max = max - min;
                heap.offer(max);
            }
            if(heap.isEmpty()){
                return 0;
            }else{
                return heap.poll();
            }
        }
    }
  • 相关阅读:
    phpstorm 破解方法
    shell_exec
    数据库配置
    sprintf
    MySQL优化步 (InnoDB)
    Python小白需要知道的 20 个骚操作!
    Python常用库整理
    Python:什么是进阶,如何进阶?
    Python中标准模块importlib详解
    Python开发【Django】:中间件、CSRF
  • 原文地址:https://www.cnblogs.com/czsy/p/10964520.html
Copyright © 2011-2022 走看看