字符串压缩
思路:
使用双指针进行模拟即可
class Solution: def compressString(self, S: str) -> str: res = [] # i:左指针,j:右指针 i, j, ls = 0, 0 ,len(S) while i < ls: # 记数当前字符的连续个数 while j < ls and S[i] == S[j]: j += 1 # 添加到结果数组 res.append(S[i]) res.append(str(j - i)) # 左指针前进 i = j # 拼接 res = ''.join(res) # 输出 return res if len(res) < ls else S
旋转矩阵
旋转公式:
\[matrix[i][j] = matrix[n - j - 1][i] \]\[matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1] \]\[matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1] \]\[matrix[j][n - i - 1] = matrix[i][j] \]其中
i
为循环行数至n//2
,j
为循环列数至(n+1)//2
,n
为行列数因此,代码为:
class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ n = len(matrix) for i in range(n // 2): for j in range((n + 1) // 2): matrix[i][j], matrix[n - j - 1][i], matrix[n - i - 1][n - j - 1], matrix[j][n - i - 1] = matrix[n - j - 1][i], matrix[n - i - 1][n - j - 1], matrix[j][n - i - 1], matrix[i][j]
零矩阵
标签:matrix,金典,List,len,---,程序员,range,ls,res From: https://www.cnblogs.com/dgqp/p/17316395.html思路:
设置两个列表记录哪里需要置零,然后对其改变即可
class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ n, m = len(matrix), len(matrix[0]) # 判断列表 rows, cols = [False] * n, [False] * m for i in range(n): for j in range(m): if matrix[i][j] == 0: # 某一个为0,将其行列记下 rows[i] = cols[j] = True for i in range(n): for j in range(m): # 如果某一个的行列别记下了为0,则直接置为0 matrix[i][j] = 0 if rows[i] or cols[j] else matrix[i][j]