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

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


Screen Shot 2017-10-07 at 10.51.46 PM.png

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


Screen Shot 2017-10-07 at 11.06.03 PM.png

2.

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


Screen Shot 2017-10-07 at 11.23.01 PM.png

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

Screen Shot 2017-10-07 at 10.07.34 PM.png

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

Screen Shot 2017-10-07 at 11.34.41 PM.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容