zoukankan      html  css  js  c++  java
  • LeetCode 531. Lonely Pixel I

    原题链接在这里:https://leetcode.com/problems/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:

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

    题解:

    Have a row array and column array to track how many B on the corresponding row or column.

    Iterate the picture for the 1st time and update row and column.

    Iterate the prictrue for the 2nd time to accumlate the count when both r[i] and c[j] == 1.

    Time Complexity: O(m*n). m = picture.length. n = picture[0].length.

    Space: O(m+n).

    AC Java:

     1 class Solution {
     2     public int findLonelyPixel(char[][] picture) {
     3         if(picture == null || picture.length == 0 || picture[0].length == 0){
     4             return 0;
     5         }
     6         
     7         int m = picture.length;
     8         int n = picture[0].length;
     9         int [] r = new int[m];
    10         int [] c = new int[n];
    11         for(int i = 0; i<m; i++){
    12             for(int j = 0; j<n; j++){
    13                 if(picture[i][j] == 'B'){
    14                     r[i]++;
    15                     c[j]++;
    16                 }
    17             }
    18         }
    19         
    20         int res = 0;
    21         for(int i = 0; i<m; i++){
    22             for(int j = 0; j<n; j++){
    23                 if(picture[i][j] == 'B' && r[i] == 1 && c[j] == 1){
    24                     res++;
    25                 }
    26             }
    27         }
    28         
    29         return res;
    30     }
    31 }
  • 相关阅读:
    NOIP2006代码及简析
    设计模式的原则
    UML应用
    关系
    活动图
    状态图
    UML概序
    UML基本图示
    用例
    介绍一个好的英语学习网站!
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11941429.html
Copyright © 2011-2022 走看看