Recca Chao 的 gitHub page

推廣網站開發,包含 Laravel 和 Kotlin 後端撰寫、自動化測試、讀書心得等。Taiwan Kotlin User Group 管理員。

View on GitHub

Kotlin Leetcode - 1470. Shuffle the Array

題目連接

class Solution {
    fun shuffle(nums: IntArray, n: Int): IntArray {
        
    }
}

解題思路

這一題考的是對陣列的處理

由於我想使用 when

但是需要處理的邏輯比較多一點

所以搭配了 also 這個 scope function 來協助表達

Kotlin 參考解答

點擊展開解答
class Solution {
    fun shuffle(nums: IntArray, n: Int): IntArray {
        val result = IntArray(nums.size)
        var j = n
        var k = 0
        nums.forEachIndexed { index, _ ->
            when {
                index % 2 != 0 -> result[index] = nums[j].also { j++ }
                else -> result[index] = nums[k].also { k++ }
            }
        }
        return result
    }
}

回到 leetcode 列表