• 【LeetCode】5638.吃苹果的最大数目


    题目链接

    5638. 吃苹果的最大数目

    题目描述

    解题思路

    贪心+优先队列

    就和平时吃零食一样,优先把快过期的零食吃完,同理,在本题中优先吃那些即将过期的苹果.

    如何才能知道现在那些苹果最快就要过期,这些快要过期的苹果又还剩余几个呢??

    利用优先队列,队列中存储的就是一个二维数组,[苹果数目,苹果过期时间].

    AC代码

    class Solution {
        public int eatenApples(int[] apples, int[] days) {
            Queue<int[]> q = new PriorityQueue<>(new Comparator<int[]>(){
                public int compare(int[] i1,int[] i2){
                    return i1[1] - i2[1];
                }
            });
            int ans = 0;
            for(int i = 0; i < apples.length; i++){
                //1.清理苹果剩余为0以及过期苹果
                while(!q.isEmpty()){
                    int[] temp = q.peek();
                    if(temp[0] <= 0 || temp[1] < i){
                        q.poll();
                    }else break;
                }
                //2.添加当天新长出的苹果,如果当天苹果数为0,则跳过
                if(apples[i] > 0){
                    int pair[] = new int[2];
                    pair[0] = apples[i];
                    pair[1] = i + days[i] - 1;
                    q.offer(pair);
                }
                //3.优先吃最早过期的.
                int temp[] = q.peek();
                if(temp != null){
                    temp[0]--;
                    ans++;  
                }
            }
            //优先队列中还存在着元素,接着吃苹果.value代表当前天数
            int value = apples.length;
            while(!q.isEmpty()){
                int temp[] = q.peek();
                if(temp[0] == 0 || temp[1] < value){
                    q.poll();
                }else{
                    temp[0]--;
                    ans++;
                    value++;
                } 
            }
            return ans;
        }
    }
    
  • 相关阅读:
    链接被点击时不出现虚线框的方法
    label 和 legend标签的用法
    了解常见的浏览器内核 Trident,Geckos,Presto,Webkit
    DOCTYPE声明的几种类型
    Angularjs基础教程
    理解angular中的module和injector,即依赖注入
    es5 api
    css3_note
    canvas 基础知识
    uglifyjs note
  • 原文地址:https://www.cnblogs.com/XDU-Lakers/p/14197094.html
Copyright © 2020-2023  润新知