Leetcode记录2-Array

为了强化训练,对题目按照分类去做,此部分为Array。

这里不对每道题都做记录。

  • 118题, Pascal’s Triangle ,给一个整数,返回杨辉三角,主要休息二维列表的使用
1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
if numRows == 0:
return []
else:
lists = []
for i in range(numRows):
lists.append([1]*(i+1))
if i > 1:
for j in range(1,i):
lists[i][j] = lists[i-1][j-1] + lists[i-1][j]
return lists
  • 121题,Best Time to Buy and Sell Stock ,最初的想法是维护两个数组,一个是记录当前price与之前每一个price的差,另一个是记录每一个price可赚得的最大收益,也就是第一个数组中每一个price对应的最大值,后来看到了相对简单的方法:
1
2
3
4
5
6
7
8
buy_price = float('inf') 
profit = 0
for price in prices:
if price < buy_price:
buy_price = price
if price - buy_price > profit:
profit = price - buy_price
return profit

:转载文章请注明出处,谢谢~