[review]531.Lonely pixel

原题是:

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].

思路是:

先横向满足,找到每行只有一个'B'的情况,并且,记录他们所在的列,并去掉其中重复的列。
再纵向满足,如果该列只有一个’B',则入选答案。

代码是:

class Solution(object):
    def findLonelyPixel(self, picture):
        """
        :type picture: List[List[str]]
        :rtype: int
        """
        ans = []
        colums = []
        
        for i in range(len(picture)):
            if picture[i].count('B') == 1:
                colums.append(picture[i].index('B'))
        
        colums = list(set(colums))
        print(colums)
        
        
        for j in colums:
            row =  [x[j] for x in picture]
            if row.count('B') == 1:
                ans.append(j)
        
       
        return len(ans) 

学到:

1.

一边遍历,一边增删改查时,要特别小心可能导致的错误。
因为被遍历的量,正在被修改。


[review]531.Lonely pixel_第1张图片
Screen Shot 2017-10-07 at 10.51.46 PM.png

可见,因为remove,越过了本该对2的遍历。


[review]531.Lonely pixel_第2张图片
Screen Shot 2017-10-07 at 11.06.03 PM.png

2.

二维数组,取列
[A for B in C] :
B 遍历 C,而A 是关于B为自变量的某个因变量(可以视作A是一个关于B的函数)


[review]531.Lonely pixel_第3张图片
Screen Shot 2017-10-07 at 11.23.01 PM.png

3.二维数组的行列互换(转置)

[review]531.Lonely pixel_第4张图片
Screen Shot 2017-10-07 at 10.07.34 PM.png

本题中由于采用了python2,因为元素不是数值,以上转置方式都出错。
python3是可以转置非数值二维数组的。

[review]531.Lonely pixel_第5张图片
Screen Shot 2017-10-07 at 11.34.41 PM.png

你可能感兴趣的:([review]531.Lonely pixel)