• leetcode刷题笔记5638题 吃苹果的最大数目


    leetcode刷题笔记5638题 吃苹果的最大数目

    地址:5638. 吃苹果的最大数目

    问题描述:

    import scala.collection.mutable.PriorityQueue
    object Solution {
        def eatenApples(apples: Array[Int], days: Array[Int]): Int = {
            val heap = PriorityQueue.empty[(Int, Int)](Ordering.by(n => n._1)).reverse
            var res = 0
            var n = apples.length
            var i = 0
    
            while (i < n || heap.length > 0){
            //while (i < 10){
                if (i < n && apples(i) > 0) {
                    heap.enqueue(((i + days(i) -1), apples(i)))
                }
                while (heap.length > 0 && heap.head._1 < i) {
                    var  temp = heap.dequeue
                }
                if (heap.length > 0) {
                    var x = heap.dequeue
                    res += 1
                    if (x._2-1 > 0) {
                        heap.enqueue((x._1, x._2-1))
                    }
                }
                i += 1 
            }
            return res
        }
    }
    
    import (
        "container/heap"
        "fmt"
    )
    
    type Item struct {
        day int
        apple int
    }
    
    type PriortyQueue []*Item
    
    func (pq PriortyQueue) Len() int {return len(pq)}
    func (pq PriortyQueue) Less(i, j int) bool {
        return pq[i].day > pq[j].day
    }
    func (pq PriortyQueue) Swap(i, j int) {
        pq[i], pq[j] = pq[j], pq[i]
    }
    
    func (pq *PriortyQueue) Push(x interface{}) {
        item := x.(*Item)
        *pq = append(*pq, item)
    }
    
    func (pq *PriortyQueue) Pop() interface{} {
        old := *pq
        n := len(old)
        item := old[n-1]
        old[n-1] = nil
        *pq = old[0:n-1]
        return item
    }
    
    func eatenApples(apples []int, days []int) int {
        pq := make(PriortyQueue, 0)
        n := len(apples)
        res := 0
        for i := 0; i <= 40000; i++ {
    
            if i < n && apples[i] > 0 {
                heap.Push(&pq, &Item{day: i+days[i]-1, apple: apples[i]})
            }
            for pq.Len() > 0 && pq[pq.Len()-1].day < i {
                _ = pq.Pop()    
            }
            if pq.Len() == 0 {continue}
            x := pq.Pop().(*Item)
            x.apple -= 1
            res += 1
            if x.apple > 0 {heap.Push(&pq, x)}
        }
        return res
    }
    
  • 相关阅读:
    android onTouchEvent
    AD smart pdf 中文丢失
    c# 定时器
    Android 绘制圆环
    52道Python面试题
    螺旋填数:读入两个整数m,n,输出一个m行n列的矩阵,这个矩阵是1~m*n这些自然数按照右、下、左、上螺旋填入的结果。
    Java经典练习题_Day04
    Java经典练习题_Day05
    Java 面向对象 初探
    Java Array 方法和使用
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/14199251.html
Copyright © 2020-2023  润新知