• 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
    }
    
  • 相关阅读:
    Async和Await的用法
    Idea有关收藏的博客
    记录看到的写的好的、实用的JavaScript博客
    Linux实用指令一
    flex布局
    移动端开发常用的vue组件
    npm --save 的含义
    切换npm源为淘宝镜像
    java String Map List 转换
    mysql查看被锁住的表
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/14199251.html
Copyright © 2020-2023  润新知