leetcode 134 加油站
# 索引在列表里循环
index = (index + 1) % len(cost)
class Solution:
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
curSum = 0
totalSum = 0
start = 0
for i in range(len(cost)):
curSum += gas[i] - cost[i]
totalSum += gas[i] - cost[i]
if curSum < 0:
curSum = 0
start = i + 1
if totalSum < 0:
return -1
return start
leetcode 135 分发糖果
先考虑从左到右,在考虑从右到左
class Solution:
def candy(self, ratings: List[int]) -> int:
n = len(ratings)
candies = [1] * n
for i in range(1, n):
if ratings[i] > ratings[i - 1]:
candies[i] = candies[i - 1] + 1
for i in range(n - 2, -1, -1):
if ratings[i] > ratings[i + 1]:
candies[i] = max(candies[i], candies[i + 1] + 1)
return sum(candies)
leetcode 860 柠檬水找零
简单题
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
five = 0
ten = 0
twenty = 0
for bill in bills:
if bill == 5:
five += 1
if bill == 10:
if five <= 0:
return False
ten += 1
five -= 1
if bill == 20:
if five > 0 and ten > 0:
five -= 1
ten -= 1
elif five >= 3:
five -= 3
else:
return False
return True
leetcode 406 根据身高重建队列
先根据身高进行第一波降序排序,第二次对数组进行插入操作
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people.sort(key = lambda x: (-x[0], x[1]))
que = []
for i in people:
que.insert(i[1], i)
return que