[LeetCode] 531. Lonely Pixel I
Given an m x n picture consisting of black 'B' and white 'W' pixels, return the number of black lonely pixels.
A black lonely pixel is a character 'B' that located at a specific position where the same row and same column don't have any other black pixels.
Example 1:
Input: picture = [["W","W","B"],["W","B","W"],["B","W","W"]] Output: 3 Explanation: All the three 'B's are black lonely pixels.
Example 2:
Input: picture = [["B","B","B"],["B","B","W"],["B","B","B"]] Output: 0
Constraints:
m == picture.lengthn == picture[i].length1 <= m, n <= 500picture[i][j]is'W'or'B'.
孤独像素。

这道题不难,我直接介绍思路。
首先我用两个数组分别记录 input 矩阵中每一行和每一列出现了多少个字母 B。之后我再次遍历 input 矩阵,当我再次遇到字母 B 的时候,我检查一下当前这个 B 是不是他所在行和所在列上唯一的一个 B。
时间O(mn)
空间O(m + n)
Java实现
1 class Solution { 2 public int findLonelyPixel(char[][] picture) { 3 int m = picture.length; 4 int n = picture[0].length; 5 int[] rows = new int[m]; 6 int[] cols = new int[n]; 7 for (int i = 0; i < picture.length; i++) { 8 for (int j = 0; j < picture[0].length; j++) { 9 if (picture[i][j] == 'B') { 10 rows[i]++; 11 cols[j]++; 12 } 13 } 14 } 15 16 int count = 0; 17 for (int i = 0; i < m; i++) { 18 for (int j = 0; j < n; j++) { 19 if (picture[i][j] == 'B' && rows[i] == 1 && cols[j] == 1) { 20 count++; 21 } 22 } 23 } 24 return count; 25 } 26 }

浙公网安备 33010602011771号