【发布时间】:2020-09-02 19:33:48
【问题描述】:
New Year Chaos Problem: Hackerrank
这是我编写的程序,它告诉我我的代码没有及时完成(我需要对其进行优化以使其在更短的时间内完成)。我已经尽我所能,但我没有想法,我该怎么办?
fun minimumBribes(q: Array<Int>) {
var bribeCount = 0
for ((i, x) in q.withIndex()) {
val last = q.lastIndex - i + 1
val first = i + 1
// Checks if any of the elements have more than 2 elements smaller than them behind them in the queue and returns out of the function if so (because no element can bribe more than 2 elements)
// Drops all the elements in the queue before x and counts the number of smaller elements after x in the queue
if (q.drop(first).count { it < x } > 2) {
println("Too chaotic")
return
}
// Adds the number of elements bigger than x that are in the queue standing ahead of x to bribeCount (since the number of bribes taken by all elements will be equal to the total number of bribes given in total and no element can get past ahead of a smaller element without bribing it)
bribeCount += q.dropLast(last).count { it > x }
}
println(bribeCount)
}
阅读页面顶部链接的第一个问题。在阅读问题陈述之前,您可能不会理解此行以下的任何内容。
如您所见,为了检查贿赂元素的人数,我计算了从该元素中具有更大价值并且在队列中站在它之前的元素的数量。通过将每个元素收到的贿赂数量相加,我们可以计算出总共提供的贿赂数量。但在此之前,我计算了小于队列中位于其后的元素的元素数量,如果该数字大于 2,则表示该元素贿赂了超过 2 个人,这是“太混乱”,我返回。
这是我收到的错误消息:Screenshot
【问题讨论】:
-
为什么
Java和Kotlin都参与了这段代码? -
我肯定在这里看不到任何 Java。我什至不懂Java。
标签: arrays performance loops kotlin