【问题标题】:Idiomatic Kotlin way to find an element to the right of a pivot that's just greater than the pivot惯用的 Kotlin 方法来查找枢轴右侧大于枢轴的元素
【发布时间】:2019-12-23 07:19:28
【问题描述】:

我想编写一个计算机程序,给定一个数字数组和一个枢轴索引,它返回比枢轴大的枢轴右侧最小元素的索引。

例如:如果输入是[1, 4, 7, 2, 5, 6],并且主元在索引1,即元素4,那么输出应该是4,这是5的索引,因为54 右侧大于 4 的最小元素。

以下代码有效

fun justGreater(nums: IntArray, pivotIndex: Int): Int {
    var result = 0
    var currBest = Int.MAX_VALUE
    for (i in pivotIndex until nums.size) {
        if (nums[i] > nums[pivotIndex] && nums[i] < currBest) {
            result = i
            currBest = nums[i]
        }
    }
    return result
}

我想写得通俗易懂。

【问题讨论】:

    标签: arrays kotlin


    【解决方案1】:

    您可以尝试以下操作:

    fun justGreater(nums: IntArray, pivotIndex: Int): Int {
        return nums.withIndex()
            .sortedBy { it.value }
            .first { it.index > pivotIndex && it.value > nums[pivotIndex] }
            .index
    }
    

    另一种选择:

    fun justGreater(nums: IntArray, pivotIndex: Int): Int {
        return nums.mapIndexed { index, number -> index to number }
            .sortedBy { (_, number) -> number }
            .first { (index, i) -> index > pivotIndex && i > nums[pivotIndex] }
            .first // returns pair, so we need to get only index
    }
    

    另一种选择:

    fun justGreater(nums: IntArray, pivotIndex: Int): Int {
        val filteredArr = nums.sliceArray(pivotIndex + 1 until nums.size)
            .filter { it > nums[pivotIndex] }
        return nums.indexOf(filteredArr.min() ?: -1) // we return -1 in case item was not found
    }
    

    【讨论】:

      【解决方案2】:

      只是一点点改进

      fun IntArray.justGreater(pivotIndex: Int): Int {
          var result = 0
          var currBest = Int.MAX_VALUE
          for (i in pivotIndex until size) {
              if (get(i) > get(pivotIndex) && get(i) < currBest) {
                  result = i
                  currBest = get(i)
              }
          }
          return result
      }
      

      我认为没有减少代码的快捷功能

      【讨论】:

        【解决方案3】:

        这将返回枢轴右侧的最小最近值位置:

        fun justGreater(nums: IntArray, pivotIndex: Int): Int {
            val least = nums.asList()
                .subList(pivotIndex + 1, nums.size)
                .filter { it > nums[pivotIndex] }
                .min()!!
            return nums.indexOf(least)
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多