C++ Using Queue


  • 0
    P
    class Solution {
    public:
        vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
           
            if(nums.size()==0 || (r *c) != nums.size() * nums[0].size()) return nums;
            
            queue<int> que;
            vector<vector<int>> res(r,vector<int>(c));// https://stackoverflow.com/questions/25937413/assigning-values-to-2d-vector-by-using-indices
            
            for(int i=0;i<nums.size();i++){
                for(int j=0;j<nums[0].size();j++){
                    que.push(nums[i][j]);
                }
            }
         
            for(int i=0;i<r;i++){
                for(int j=0;j<c;j++){
                        res[i][j] =  que.front(); 
                        que.pop();
                }
            }
            return res;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.