LC 1337. The K Weakest Rows in a Matrix

Nilanjan Deb · April 5, 2020

This is my CPP solution.

class Solution {
public:
    vector<int> kWeakestRows(vector<vector<int>>& mat, int k) {
        int m = mat.size(), n = mat[0].size();
        vector<vector<int>> freq;
        vector<int> row;
        for(int j=0;j<=n;j++){
            freq.push_back(row);
        }
        for(int i = 0;i<m ;i++){
            int cnt = 0;
            for(int j=0;j<n;j++){
                if(mat[i][j] == 0)
                    break;
                cnt++;
            }
            freq[cnt].push_back(i);
        }
        for(int i=0;i<=n;i++){
            for(int j=0;j<freq[i].size();j++){
                row.push_back(freq[i][j]);
            }
        }
        for(int i=row.size()-1;i>=k;i--){
            row.pop_back();
        }
        return row;
    }
};


Dicussion Forum