美文网首页
531. Lonely Pixel I

531. Lonely Pixel I

作者: matrxyz | 来源:发表于2018-01-13 17:10 被阅读0次

    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:

    思路:
    这道题定义了一种孤独的黑像素,就是该黑像素所在的行和列中没有其他的黑像素,让我们找出所有的这样的像素。那么既然对于每个黑像素都需要查找其所在的行和列,为了避免重复查找,我们可以统一的扫描一次,将各行各列的黑像素的个数都统计出来,然后再扫描所有的黑像素一次,看其是否是该行该列唯一的存在,是的话就累加计数器即可
    (也可以在原数组上存,减少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;
        }
    
    }
    

    相关文章

      网友评论

          本文标题:531. Lonely Pixel I

          本文链接:https://www.haomeiwen.com/subject/kkncoxtx.html