Given a 2D grid
of size m x n
and an integer k
. You need to shift the grid
k
times.
In one shift operation:
- Element at
grid[i][j]
moves togrid[i][j + 1]
. - Element at
grid[i][n - 1]
moves togrid[i + 1][0]
. - Element at
grid[m - 1][n - 1]
moves togrid[0][0]
.
Return the 2D grid after applying shift operation k
times.
Example 1:
Input:grid
= [[1,2,3],[4,5,6],[7,8,9]], k = 1 Output: [[9,1,2],[3,4,5],[6,7,8]]Example 2:
Input:grid
= [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4 Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]Example 3:
Input:grid
= [[1,2,3],[4,5,6],[7,8,9]], k = 9 Output: [[1,2,3],[4,5,6],[7,8,9]]
Constraints:
m == grid.length
n == grid[i].length
1 <= m <= 50
1 <= n <= 50
-1000 <= grid[i][j] <= 1000
0 <= k <= 100
二维网格迁移。
一开始审题的时候,直观感觉这个题很像54题那一类matrix的题型,一直在想有没有不用额外空间或者原地修改matrix的做法。首先我给一个朴素的解法。思路是先遍历matrix,把每个元素按顺序放入一个双端队列deque中。将K % mn之后,把元素再按序放到list。最后输出的是list of list。
时间O(mn)
空间O(n) - queue
Java实现
1 class Solution { 2 public List<List<Integer>> shiftGrid(int[][] grid, int k) { 3 int m = grid.length; 4 int n = grid[0].length; 5 List<List<Integer>> res = new ArrayList<>(); 6 Deque<Integer> queue = new ArrayDeque<>(); 7 for (int i = 0; i < m; i++) { 8 for (int j = 0; j < n; j++) { 9 queue.add(grid[i][j]); 10 } 11 } 12 for (int i = 0; i < k; i++) { 13 queue.addFirst(queue.pollLast()); 14 } 15 for (int i = 0; i < m; i++) { 16 List<Integer> temp = new ArrayList<>(); 17 for (int j = 0; j < n; j++) { 18 temp.add(queue.poll()); 19 } 20 res.add(new ArrayList<Integer>(temp)); 21 } 22 return res; 23 } 24 }
不使用deque的方法如下。因为结果集是list of list,所以并不涉及到对原input matrix中元素的移动,你只需要确定结果集的每个list放的元素是来自matrix的哪些坐标即可。首先K还是要去 % 一下matrix的总长度m * n,这样就知道K到底在matrix的什么位置。同时需要把这个二维坐标转换成一维的,这样便于计算。16行的减K相当于是去找原matrix中前K个位置上的那个元素。
时间O(mn)
空间O(1)
Java实现
1 class Solution { 2 public List<List<Integer>> shiftGrid(int[][] grid, int k) { 3 List<List<Integer>> res = new ArrayList<>(); 4 int m = grid.length; 5 int n = grid[0].length; 6 // total length of the matrix 7 int total = m * n; 8 k = k % total; 9 // create all the sub lists 10 for (int i = 0; i < m; i++) { 11 res.add(new ArrayList<>()); 12 } 13 // start to put elements into lists 14 // 2d to 1d 15 for (int l = 0; l < total; l++) { 16 int index = (l - k + total) % total; 17 res.get(l / n).add(grid[index / n][index % n]); 18 } 19 return res; 20 } 21 }