LeetCode 531. Longly 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].

 


题目标签:Array

  题目给了我们一个2d picture array,让我们找出有几个孤独的像素B。孤独的像素B的行和列中只有自己一个像素。

  可以建立2个 array, 分别是 row 和 col, 它们的size 就是picture里的行和列的size。

  第一次遍历picture:如果是B,就把B的row 和 column 在 row array 和 col array 里对应位置 加1。目的是为了记录每一行和每一列里有多少个B。

  第二次遍历picture:如果是B,就到对应的 row  和 col array 里, 如果 row 和 col 的值都是1 的话,说明这一个B 是 row 这一行里, 和 col 这一列里唯一的B。累计计数到res。

 

Java Solution:

Runtime beats 80.41% 

完成日期:09/24/2017

关键词:Array

关键点:设立row array & col array 记录每一行每一列里有多少个B;孤单像素所在的行和列只有它自己

 1 class Solution 
 2 {
 3     public int findLonelyPixel(char[][] picture) 
 4     {
 5         int n = picture.length;
 6         int m = picture[0].length;
 7         // create two array for counting B
 8         int[] row = new int[n];
 9         int[] col = new int[m];
10         
11         int res = 0; // counts longly black
12         
13         // 1st iteration, if find a B, increase its row and col number in two array
14         for(int i=0; i<n; i++)
15         {
16             for(int j=0; j<m; j++)
17             {
18                 if(picture[i][j] == 'B')
19                 {
20                     row[i]++;
21                     col[j]++;
22                 }
23             }
24         }
25         
26         
27         // 2nd iteration, if find a B, check its row and col are both 1, meaning lonly B
28         for(int i=0; i<n; i++)
29             for(int j=0; j<m; j++)
30                 if(picture[i][j] == 'B' && row[i] == 1 && col[j] == 1)
31                     res++;
32                     
33         return res;
34     }
35 }

参考资料:

https://discuss.leetcode.com/topic/81680/java-o-nm-time-with-o-n-m-space-and-o-1-space-solutions

 

LeetCode 题目列表 - LeetCode Questions List

 

posted @ 2017-09-25 11:36  Jimmy_Cheng  阅读(431)  评论(0编辑  收藏  举报