Recca Chao 的 gitHub page

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

View on GitHub

Kotlin Leetcode - 1476. Subrectangle Queries

題目連接

class SubrectangleQueries(rectangle: Array<IntArray>) {

    fun updateSubrectangle(row1: Int, col1: Int, row2: Int, col2: Int, newValue: Int) {
        
    }

    fun getValue(row: Int, col: Int): Int {
        
    }

}

/**
 * Your SubrectangleQueries object will be instantiated and called as such:
 * var obj = SubrectangleQueries(rectangle)
 * obj.updateSubrectangle(row1,col1,row2,col2,newValue)
 * var param_2 = obj.getValue(row,col)
 */

解題思路

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

利用 var 關鍵字建立陣列

updateSubrectangle 將值放進去陣列

getValue 將值從陣列取出

Kotlin 參考解答

class SubrectangleQueries(var rectangle: Array<IntArray>) {

    fun updateSubrectangle(row1: Int, col1: Int, row2: Int, col2: Int, newValue: Int) {
        for (x in row1..row2) {
            for (y in col1..col2) {
                rectangle[x][y] = newValue
            }
        }
    }

    fun getValue(row: Int, col: Int) = rectangle[row][col]

}

回到 leetcode 列表