【问题标题】:Duplicate Zeros in KotlinKotlin 中的重复零
【发布时间】:2022-07-29 20:42:14
【问题描述】:

我正在解决一个数组问题。

给定一个固定长度的整数数组arr,复制每个出现的零,将剩余的元素向右移动。

注意,超出原始数组长度的元素不会被写入。对输入数组进行上述修改,不返回任何内容。

示例 1:

Input: arr = [1,0,2,3,0,4,5,0]
Output: [1,0,0,2,3,0,0,4]

示例 2:

Input: arr = [1,2,3]
Output: [1,2,3]

我尝试了这个解决方案,但我得到了错误的输出

class Solution {
    fun duplicateZeros(arr: IntArray): Unit {
        arr.forEachIndexed { index, value ->
            if(value == 0 && ((arr.size - 1) != index)) {
                arr[index + 1] = 0
            }
        }
    }
}

实际输出

[1,0,0,0,0,0,0,0]

预期输出

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

注意请不要复制数组。我想在同一个数组中求解。谁能指导我我的逻辑哪里错了,我该如何解决这个问题?

谢谢

【问题讨论】:

  • 这似乎是学习如何debug 你的程序的好时机。例如,通过在 debugger 中逐句逐句执行它,同时监视变量及其值。
  • arr[0],第一个值,您的循环看到1 - 它什么也不做。在第二个值arr[1],它看到0,并将arr[2] 设置为0 - 覆盖现有的2。接下来它转到arr[2](它刚刚覆盖的那个),看到​​0,然后用0 覆盖arr[3]3)。您的循环不会插入新元素,它会在看到的第一个 0 之后用 0 覆盖所有内容。
  • “请不要复制数组” 为什么不呢?使用a collection builder 会使逻辑更加清晰。 Kotlin 鼓励不可变数据结构是有原因的——它们通常不那么容易出错。
  • 那么在那个地方插入 0 时我们如何快速下一个元素呢?
  • 在第一次出现 0 时,您将 0 写入您将在迭代时读取的下一个索引,因此它将一直向下推零。您需要在覆盖之前读取下一个值。

标签: kotlin data-structures


【解决方案1】:

从 cmets 看来,您在这个问题上一直做得很好。我希望在这里添加一些代码不会破坏进一步的学习过程。我还添加了一个使用fold 的版本,只是为了比较行数。代码是在 Kotest 中编写的。

given("a StackOverflow issue") {

    val expectedArray = arrayOf(1, 0, 0, 2, 3, 0, 0, 4)

    `when`("duplicating zeroes") {

        val arr = arrayOf(1, 0, 2, 3, 0, 4, 5, 0)
        var outerIndex = 0

        do {
            if (arr[outerIndex] == 0) {

                /** shuffle items one position to the right */
                for (innerIndex in arr.size - 1 downTo outerIndex + 2) {
                    arr[innerIndex] = arr[innerIndex - 1]
                    println("Array is now ${arr.contentToString()}")
                }

                /** bump index and set zero */
                arr[++outerIndex] = 0
            }

            /** we're going to stop after the second last item, no point inspecting the last item */
        } while (++outerIndex < arr.size - 1)

        then("result should be as expected") {
            arr shouldBe expectedArray
        }
    }

    `when`("duplicating zeroes with fold") {

        val arr = arrayOf(1, 0, 2, 3, 0, 4, 5, 0)

        val resultUsingFold = arr.fold(mutableListOf<Int>()) { accumulator, item ->
            accumulator.also { innerAcc ->
                repeat(if (item == 0) 2 else 1) { innerAcc.add(item) }
            }
        }.slice(arr.indices)

        then("result should be as expected") {
            resultUsingFold shouldBe expectedArray
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 2012-01-21
    • 2017-05-28
    • 2013-03-03
    • 2014-07-09
    相关资源
    最近更新 更多