LeetCode in Kotlin

1834. Single-Threaded CPU

Medium

You are given n tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, where tasks[i] = [enqueueTimei, processingTimei] means that the ith task will be available to process at enqueueTimei and will take processingTimei to finish processing.

You have a single-threaded CPU that can process at most one task at a time and will act in the following way:

Return the order in which the CPU will process the tasks.

Example 1:

Input: tasks = [[1,2],[2,4],[3,2],[4,1]]

Output: [0,2,3,1]

Explanation: The events go as follows:

Example 2:

Input: tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]

Output: [4,3,2,0,1]

Explanation: The events go as follows:

Constraints:

Solution

import java.util.PriorityQueue

class Solution {
    fun getOrder(tasks1: Array<IntArray>): IntArray {
        val n = tasks1.size
        val tasks = Array(n) { IntArray(3) }
        for (i in 0 until n) {
            tasks[i] = intArrayOf(tasks1[i][0], tasks1[i][1], i)
        }
        tasks.sortWith(compareBy { a: IntArray -> a[0] })
        val minHeap = PriorityQueue(
            Comparator { a: IntArray, b: IntArray ->
                return@Comparator if (a[1] == b[1]) {
                    a[2] - b[2]
                } else {
                    a[1] - b[1]
                }
            },
        )
        var time = tasks[0][0]
        val taskOrderResult = IntArray(n)
        var i = 0
        var index = 0
        while (minHeap.isNotEmpty() || i < n) {
            while (i < n && time >= tasks[i][0]) {
                minHeap.add(tasks[i++])
            }
            if (minHeap.isNotEmpty()) {
                val task = minHeap.remove()
                taskOrderResult[index++] = task[2]
                time += task[1]
            } else {
                time = tasks[i][0]
            }
        }
        return taskOrderResult
    }
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy