C++ Another view to see lonely black, faster at sparse Matrix


  • 0
    F

    A lonely B takes one 1 count at both row and col counter
    So when accumulate, only take O(m+n) time complexity.

    class Solution {
    public:
        int findLonelyPixel(vector<vector<char>>& pic) {
            int ans=0;
            int m=pic.size();
            int n=pic[0].size();
            vector<int> row(m,0);
            vector<int> col(n,0);
            for(int i=0;i<pic.size();i++){
                for(int j=0;j<pic[0].size();j++){
                    if(pic[i][j]=='B'){
                        row[i]++;col[j]++;
                    }
                }
            }
            int mm=0,nn=0;
            for(auto& it:row){
                if(it==1)mm++;
            }
            for(auto& it:col){
                if(it==1)nn++;
            }
    //every lonely B take exactly one 1 at row[] and one 1 at col[]
            return min(mm,nn);
        }
    };
    

Log in to reply
 

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