g1201_1300.s1260_shift_2d_grid.Solution.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-kotlin Show documentation
Show all versions of leetcode-in-kotlin Show documentation
Kotlin-based LeetCode algorithm problem solutions, regularly updated
package g1201_1300.s1260_shift_2d_grid
// #Easy #Array #Matrix #Simulation #2023_06_08_Time_302_ms_(100.00%)_Space_38.7_MB_(100.00%)
class Solution {
fun shiftGrid(grid: Array, k: Int): List> {
val flat = IntArray(grid.size * grid[0].size)
var index = 0
for (ints in grid) {
for (j in grid[0].indices) {
flat[index++] = ints[j]
}
}
val mode = k % flat.size
var readingIndex = flat.size - mode
if (readingIndex == flat.size) {
readingIndex = 0
}
val result: MutableList> = ArrayList()
for (i in grid.indices) {
val eachRow: MutableList = ArrayList()
for (j in grid[0].indices) {
eachRow.add(flat[readingIndex++])
if (readingIndex == flat.size) {
readingIndex = 0
}
}
result.add(eachRow)
}
return result
}
}