0%

leetcode-useful-code

记录一些刷Leetcode时候遇到的有用的代码

  1. 反转数组
1
2
3
>>> temp = [1,2,3,4]
>>> temp[::-1]
[4, 3, 2, 1]
  1. zip后的列表排序
1
2
3
4
5
>>> temp = [4,2,1,3]
>>> order = [0,1,2,3]
>>> result = sorted(zip(temp,order), key=lambda x:x[0])
>>> result
[(1, 2), (2, 1), (3, 3), (4, 0)]
  1. 二维数组的初始化

错误示例:

1
dp = [[0]*m]*n

正确示例:

1
dp = [[0]*m for _ in range(n)]