想到后面觉得好难
board = [['X', ' . ', ' . '],
[' . ', ' . ', 'X'],
[' . ', ' . ', 'X'],
[' . ', ' . ', ' X ', ]]
记录一下我的挣扎:
if not filter(lambda x:x<len(board[0]),[row.count('X') for row in board]):
if board[0].count('X')>0:
return 1
else:
return 0 #[['X']]
#maxx = max(filter(lambda x:x<len(board[0]),[row.count('X') for row in board]))
maxx = max(lambda x:x<len(board[0]),[row.count('X') for row in board])
if maxx != len(board[0])
maxx = max(maxx, max(filter(lambda x:x<len(board),[[row[col] for row in board].count('X') for col in range(len(board[0])) ])))
if maxx==0:
if board[0].count('X')>0:
return 1
else:
return 0 #[['X','X','X']]
return maxx
啊 后来我的思路稍微正了一些,但是只想到怎么判断右边和下边把船概括进来而没有想到把左边和上边的排除即可。。
注意python没有||,而&,|,^分别代表与或非的位运算,逻辑运算还是老老实实and,or,not
28.91%
class Solution(object):
def countBattleships(self, board):
"""
:type board: List[List[str]]
:rtype: int
"""
cnt = 0
for i in range(len(board)):
for j in range(len(board[0])):
#board[i][j] right:board[i][j+1] down:board[i+1][j]
if board[i][j]=='X'and(i==0 or board[i-1][j]=='.')and(j==0 or board[i][j-1]=='.'):
cnt += 1
return cnt
-----------------------------------------
震惊!头一次碰到100% 42ms
note1:判断(大于或小于) 比 (不等于或等于)效率要高
note2:zip() 返回元组组成的列表
class Solution(object):
def countBattleships(self, board):
"""
:type board: List[List[str]]
:rtype: int
"""
return sum(zip(r,['.']+r,p or'.'*len(r)).count(tuple('X..'))for r,p in zip(board,[0]+board))
疑似推导过程?。。
def countBattleships(self, b):
#return sum(all([b[y][x]=='X',x<1 or b[y][x-1]!='X',y<1 or b[y-1][x]!='X']) for y in range(len(b)) for x in range(len(b[0])))
#return sum(all([b[y][x]>'.', x<1 or b[y][x-1] <'X',y<1 or b[y-1][x]< 'X']) for y in range(len(b)) for x in range(len(b[0])))
#return sum(all([b[y][x]>'.', x<1 or 'X'>b[y][x-1], y<1 or 'X'>b[y-1][x]]) for y in range(len(b))for x in range(len(b[0])))
#return sum(all([c>'.',x<1or'X'>r[x-1],y<1or'X'>b[y-1][x]])for y,r in enumerate(b) for x,c in enumerate(r))
return sum(zip(r,['.']+r,p or'.'*len(r)).count(tuple('X..'))for r,p in zip(b,[0]+b))
------------------------------------
天啦噜又一个100% 其实所有都是第一种思想的变体。这一个的优点在于遍历每个点的时候判断的条件优化了。排除速度更快相当于数数速度更快。
以及受到欺骗,这里用了其他的变量空间,严格来说并不符合题目要求的memory为O(1)
class Solution(object):
def countBattleships(self, board):
"""
:type board: List[List[str]]
:rtype: int
"""
cols = len(board)
rows = len(board[0])
ct = 0
for c in xrange(cols):
for r in xrange(rows):
# We count a battleship only first time we see it. If a battleship piece 'X'
# is encountered, it is only new if neither the upper or left components are not also
# pieces of the same battleship. These prior indices are guarenteed to already be explored by
# the time we get to the current board index.
if board[c][r] != 'X':
continue
if r > 0 and board[c][r - 1] == 'X':
continue
if c > 0 and board[c - 1][r] == 'X':
continue
ct += 1
return ct