第一题
def GetMaxConsecutiveOnes(self, arr, k):
# write code here
zero = 0
left = 0
res = 0
for right in range(len(arr)):
if arr[right] == 0:
zero += 1
while zero > k:
if arr[left] == 0:
zero -= 1
left += 1
res = max(res, right - left + 1)
return res
第二题
def SpiralMatrix(self, matrix):
# write code here
direction = [[0, 1], [1, 0], [0, -1], [-1, 0]]
res = []
x, y = 0, 0
direct = 0
for _ in range(len(matrix) * len(matrix[0]) - 1):
res.append(matrix[x][y])
matrix[x][y] = 'a'
while not (0 <= x + direction[direct][0] < len(matrix) and
len(matrix[0]) > y + direction[direct][1] >= 0 and
matrix[x + direction[direct][0]][y + direction[direct][1]] != 'a'):
direct = (direct + 1) % 4
x += direction[direct][0]
y += direction[direct][1]
res.append(matrix[x][y])
return res
第三题
def GetFragment(self, str):
slide = 1
for i in range(1, len(str)):
if str[i] != str[i - 1]:
slide += 1
return len(str) // slide
全部评论
(0) 回帖