作差,从0索引开始遍历,currentsum若为0 ,从当前索引的下一个索引重新开始遍历,保证currentsun一直大于0
一定要注意先判断是否有解!不然会超时!
class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
diff = []
for i in range(len(gas)):
diff.append(gas[i] - cost[i])
if sum(diff)<0:#先判断是不是有结果
return -1
currentsum = 0
startindex = 0
i = startindex
count = 0
while count <= len(diff):
currentsum += diff[i]
if currentsum < 0:
startindex = (i+1) % len(diff)
count = 0
currentsum = 0
i = startindex
else:
i = (i+1) % len(diff)
count += 1
if count == len(diff):
return startindex
第二题
二维排序问题,先从左往右排序,再从右往左排。注意拍完之后要去左右两次结果的max数值
class Solution(object):
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
nums=[1]*len(ratings)
for i in range(len(ratings)-1):
if ratings[i+1] > ratings[i]:
nums[i+1] = nums[i] + 1
for i in range(len(ratings)-1,0,-1):
if ratings[i-1] > ratings[i]:
nums[i-1] = max(nums[i]+1,nums[i-1])
return sum(nums)
第三题
简单,注意收20块的两种找零情况
class Solution(object):
def lemonadeChange(self, bills):
"""
:type bills: List[int]
:rtype: bool
"""
table={}
for i in range(len(bills)):
if bills[i] == 5:
table['5']=table.get('5', 0) + 1
if bills[i] == 10:
table['5']=table.get('5', 0) - 1
table['10']=table.get('10', 0) + 1
if bills[i] == 20:
if table.get('10', 0) ==0:
table['5']=table.get('5', 0) - 3
else:
table['5']=table.get('5', 0) - 1
table['10']=table.get('10', 0) - 1
table['20']=table.get('10', 0) + 1
if table.get('5', 0) <0 or table.get('10', 0) <0 or table.get('20', 0)<0:
return False
return True
第四题
# 先按照h维度的身高顺序从高到低排序。确定第一个维度
# lambda返回的是一个元组:当-x[0](维度h)相同时,再根据x[1](维度k)从小到大排序
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])) # -x[0]表示降序,x[1]表示升序
que=[ ]
for p in people:
que.insert(p[1],p)
return que
# 根据每个元素的第二个维度k,贪心算法,进行插入
# people已经排序过了:同一高度时k值小的排前面。