Skip to content

1260_Shift2DGrid

a920604a edited this page Apr 14, 2023 · 1 revision

title: 1260. Shift 2D Grid tags: - hash table categories: leetcode comments: false

solution

option 1

class Solution {
public:
    vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
        vector<int> vec;
        int n =grid.size(), m=grid[0].size();
        for(int i=0;i<n;++i){
            for(int j = 0;j<m;++j){
                vec.push_back(grid[i][j]);
            }
        }
        k%= m*n;
        k = m*n-k;
        for(int i=0;i<n;++i){
            for(int j = 0;j<m;++j){
                grid[i][j] = vec[k%(m*n)];
                k++;
            }
        }
        return grid;
    }
};

option 2 - O(1)

analysis

  • time complexity O(mn)
  • space complexity O(nm) O(1)
Clone this wiki locally