原题是:
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.
一边遍历,一边增删改查时,要特别小心可能导致的错误。
因为被遍历的量,正在被修改。
可见,因为remove,越过了本该对2的遍历。
2.
二维数组,取列
[A for B in C] :
B 遍历 C,而A 是关于B为自变量的某个因变量(可以视作A是一个关于B的函数)
3.二维数组的行列互换(转置)
本题中由于采用了python2,因为元素不是数值,以上转置方式都出错。
python3是可以转置非数值二维数组的。