在 Kotlin 上计算数组中 max int 的行数更少,并且比 O(nlogn) 更快?

UmA*_*orn 2 algorithm kotlin

我想知道是否有更好的方法或惯用的方法来使用 Kotlin 计算数组中的最大 int 并且比 O(nlogn) 更快?

这段代码给出了 O(n) 但我觉得它太长了

fun countMax(n: Int, ar: Array<Int>): Int {
   val max = ar.max();
    var countMax = 0
    for(i in ar)
        if(i==max)
            countMax++

                return countMax
}

fun main(args: Array<String>) {
    val scan = Scanner(System.`in`)

    val n = scan.nextLine().trim().toInt()

    val ar = scan.nextLine().split(" ").map{ it.trim().toInt() }.toTypedArray()

    val result = birthdayCakeCandles(n, ar)

    println(result)
}
Run Code Online (Sandbox Code Playgroud)

排序然后计数得到 nlogn

val input: Scanner = if (inputFile.exists()) Scanner(inputFile) else Scanner(System. in)

fun main(args: Array<String>) {
  input.nextLine()
  val nums = input.nextLine().split(' ').map { it.toLong() }.sorted()
  val s = nums.takeLastWhile { it == nums.last() }.size
  print(s)
}
Run Code Online (Sandbox Code Playgroud)

我想知道有更短的代码并且比 O(nlogn) 执行得更快

s1m*_*nw1 5

你可以这样做:

fun countMax(ar: Array<Int>) = 
    ar.max().let { max -> ar.count { it == max } }
Run Code Online (Sandbox Code Playgroud)

计算最大值,max然后使用count以获取该最大值在数组中的出现次数。

或者,将值分组,以 max 为键提取组,并映射到大小:

fun countMax(ar: Array<Int>) = 
    ar.groupBy { it }.maxBy { it.key }?.value?.size
Run Code Online (Sandbox Code Playgroud)

  • 另一种更有效的分组方法是:`ar.groupingBy { it }.eachCount().maxBy { it.key }?.value` (2认同)