531. Lonely Pixel I

Given a picture consisting of black and white pixels, find the number of black lonely pixels.
The picture is represented by a 2D char array consisting of 'B' and 'W', which means black and white pixels respectively.
A black lonely pixel is character 'B' that located at a specific position where the same row and same column don't have any other black pixels.

Example:
Input: 
[['W', 'W', 'B'],
 ['W', 'B', 'W'],
 ['B', 'W', 'W']]

Output: 3
Explanation: All the three 'B's are black lonely pixels.

Note:
The range of width and height of the input 2D array is [1,500].

Solution1:

思路:
這道題定義了一種孤獨的黑像素,就是該黑像素所在的行和列中沒有其他的黑像素,讓我們找出所有的這樣的像素。那么既然對于每個黑像素都需要查找其所在的行和列,為了避免重復(fù)查找,我們可以統(tǒng)一的掃描一次,將各行各列的黑像素的個數(shù)都統(tǒng)計出來,然后再掃描所有的黑像素一次,看其是否是該行該列唯一的存在,是的話就累加計數(shù)器即可
(也可以在原數(shù)組上存,減少Space)
Time Complexity: O(mn) Space Complexity: O(m+n)

https://leetcode.com/problems/lonely-pixel-i/discuss/100018/

Solution1 Code:

class Solution {
    public int findLonelyPixel(char[][] picture) {
        int n = picture.length, m = picture[0].length;

        int[] rowCount = new int[n], colCount = new int[m];
        for (int i=0;i<n;i++) {
            for (int j=0;j<m;j++) { 
                if (picture[i][j] == 'B') { 
                    rowCount[i]++; colCount[j]++; 
                }
            }
        }

        int count = 0;
        for (int i=0;i<n;i++) {
            for (int j=0;j<m;j++) { 
                if (picture[i][j] == 'B' && rowCount[i] == 1 && colCount[j] == 1) count++;
            }
        }

        return count;
    }

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容