C++ solution using hashmap


  • 0
    A

    Iterate the pixels, if it is 'B' increment the row and col counter for the index i and j respectively.

    Iterate the pixels again, if it is 'B' and both counters are 1, this is the lonely pixel.

    Runtime: O(N*M)
    Space: O(max(N,M))

    class Solution {
    public:
        int findLonelyPixel(vector<vector<char>>& picture) {
            unordered_map<int, int> rowCount;
            unordered_map<int, int> colCount;
            
            int result = 0;
            for (int i = 0; i < picture.size(); ++i) {
                for (int j = 0; j < picture[i].size(); ++j) {
                    if (picture[i][j] == 'B') {
                        rowCount[i]++;
                        colCount[j]++;
                    }
                }
            }
            
            for (int i = 0; i < picture.size(); ++i) {
                for (int j = 0; j < picture[i].size(); ++j) {
                    if (picture[i][j] == 'B' && rowCount[i] == 1 && colCount[j] == 1) {
                        ++result;
                    }
                }
            }
            return result;
        }
    };
    

Log in to reply
 

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