0066、加一
class Solution:
def plusOne(self, digits):
for i in range(len(digits) - 1, -1, -1):
digits[i] = (digits[i] + 1) % 10
if digits[i]:
return digits
return [1] + digits
0724、寻找数组的中心下标
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
numSum = sum(nums)
leftSum = 0
for i in range(len(nums)):
if numSum - leftSum -nums[i] == leftSum:
return i
leftSum += nums[i]
return -1
0189、旋转数组
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
k %= n
nums.reverse()
nums[:k] = list(reversed(nums[:k]))
nums[k:] = list(reversed(nums[k:]))
0048、旋转图像
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
pos1,pos2 = 0,len(matrix)-1
while pos1<pos2:
add = 0
while add < pos2-pos1:
temp = matrix[pos2-add][pos1]
matrix[pos2-add][pos1] = matrix[pos2][pos2-add]
matrix[pos2][pos2-add] = matrix[pos1+add][pos2]
matrix[pos1+add][pos2] = matrix[pos1][pos1+add]
matrix[pos1][pos1+add] = temp
add = add+1
pos1 = pos1+1
pos2 = pos2-1
0054、螺旋矩阵(没有想出来,无奈看了参考答案)
0498、对角线遍历(参考了答案)
class Solution:
def findDiagonalOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix or not matrix[0]:
return []
N, M = len(matrix), len(matrix[0])
result, intermediate = [], []
for d in range(N + M - 1):
intermediate.clear()
r, c = 0 if d < M else d - M + 1, d if d < M else M - 1
while r < N and c > -1:
intermediate.append(matrix[r][c])
r += 1
c -= 1
if d % 2 == 0:
result.extend(intermediate[::-1])
else:
result.extend(intermediate)
return result