解题套路:
- 将二维数组用一维索引表示;
- 在一维数组上进行变换【通常是分段反转再反转、交换等等】;
- 根据一维索引访问、修改二维数组的元素,通常结合两个方法,set & get
class Solution:
def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
m, n = len(grid), len(grid[0])
mn = m*n
k = k % mn
# 先对整个一维数组反转
self.reverse(grid, 0, mn-1)
# 再反转前k个
self.reverse(grid, 0, k-1)
# 最后反转 mn-k 个
self.reverse(grid, k, mn-1)
return grid
def reverse(self, grid, left, right):
while left < right:
tmp = self.get(grid, left)
self.set(grid, left, self.get(grid, right))
self.set(grid, right, tmp)
left += 1
right -= 1
# 通过一维数组的索引,访问二维数组的元素
def get(self, grid, index):
n = len(grid[0])
row = index // n
col = index % n
return grid[row][col]
# 通过一维数组的索引,修改二维数组的元素
def set(self, grid, index, val):
n = len(grid[0])
row = index // n
col = index % n
grid[row][col] = val