思路:首先如果gas的总和小于cost的总和,那么无论如何都跑不到一圈。接下来就算每天的rest[i] = gas[i] - cost[i]。如果当天的rest累加为负值时,那么就不可能从当前位置出发跑一圈。也就是要从下一个七点开始重新累计。
class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
if sum(gas) < sum(cost):
return -1
rest = [gas[i] - cost[i] for i in range(len(gas))]
curSum = 0
totalSum = 0
startIndex = 0
for i in range(len(rest)):
curSum += rest[i]
if curSum < 0:
startIndex = i + 1
curSum = 0
return startIndex
思路:想到了两次贪心的思路,但是从后向前的result[i]的设置没有考虑周全,因为有两种选择。一:如果本身result[i-1] 的值就比result[i]大的话就选result[i-1],如果两个相等就选result[i]+1
class Solution(object):
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
result = [1] * len(ratings)
for i in range(len(result) - 1):
if ratings[i+1] > ratings[i]:
result[i+1] = result[i] + 1
for i in range(len(result) -1, 0, -1):
if ratings[i-1] > ratings[i]:
result[i-1] = max(result[i] + 1, result[i - 1])
return sum(result)
题目链接:860. 柠檬水找零 - 力扣(LeetCode)
思路:模拟题
class Solution(object):
def lemonadeChange(self, bills):
"""
:type bills: List[int]
:rtype: bool
"""
five = 0
ten = 0
twenty = 0
for x in bills:
if x == 5:
five += 1
elif x == 10:
if five <= 0:
return False
else:
ten += 1
five -= 1
elif x == 20:
if ten <= 0:
if five < 3:
return False
else:
five -= 3
else:
if five <= 0:
return False
else:
five -= 1
ten -= 1
return True
题目链接:406. 根据身高重建队列 - 力扣(LeetCode)
思路:对身高进行排序,然后根据后序的值将元组插入新数组。
class Solution(object):
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
people.sort(key = lambda x : (-x[0], x[1]))
result = []
for x in people:
result.insert(x[1], x)
return result