class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
curSum = 0;
minSum = float('inf')
for i in range(len(gas)) :
rest = gas[i] - cost[i]
curSum += rest;
if curSum < minSum :
minSum = curSum
if curSum < 0 :
return -1
if minSum >= 0:
return 0
for i in range(len(gas) - 1, -1, -1):
rest = gas[i] - cost[i]
minSum += rest
if minSum >= 0 :
return i
return -1
先从前先后遍历,按ratings大小比较 + 1;再从后向前遍历,需要一个取最大。
class Solution(object):
def candy(self, ratings):
n = len(ratings)
candy = [1]*n
for i in range(1, n):
if ratings[i] > ratings[i - 1]:
candy[i] = candy[i - 1] + 1
for i in range(n - 2, -1, -1):
if ratings[i] > ratings[i + 1]:
candy[i] = max(candy[i], candy[i + 1] + 1)
return sum(candy)
这里用三个整形变量存储就行了,用字典是为了练习一下
class Solution(object):
def lemonadeChange(self, bills):
n = len(bills)
_dict = Counter()
for i in range(n):
if bills[i] == 5:
_dict["five"] += 1
if bills[i] == 10:
_dict["ten"] += 1
_dict["five"] -= 1
if _dict["five"] < 0:
return False
if bills[i] == 20 :
_dict["two"] += 1
if _dict['ten'] > 0 :
_dict['ten'] -= 1
_dict['five'] -= 1
else :
_dict['five'] -= 3
if _dict['ten'] < 0 or _dict['five'] < 0:
return False
return True
class Solution(object):
def reconstructQueue(self, people):
people.sort(key = lambda x: (-x[0], x[1]))
que = []
for p in people :
que.insert(p[1], p)
return que