https://leetcode-cn.com/problems/gas-station/solution/134jia-you-zhan-pythonbao-li-tan-xin-shu-678o/
难度:中等
暴力解法: 初看这道题,暴力解法大家应该都能想到,以每一个点为出发点尝试循环。 当循环的index大于len(gas)时,我们针对index对len(gas)求余即可始终保持数组下标不越界。 这种方式的复杂度为O(n**2),虽然这道题通过了,但是还是很有超时风险的。 贪心算法 在面试和日常刷题汇总,贪心思维的考点还是比较多的,同样的这道题也可以通过贪心的做法来实现。 首先我们需要判断如果sum(gas) < sum(cost),那么无论如何选择都没办法满足条件。 反之,如果sum(gas) >= sum(cost),那么总有一点开始是可以满足条件的。
此时,我们从gas[0]开始判断,如果gas[0] < cost[0],我们就选择下一个节点。 但如果我们gas[i] > cost[i] 但 gas[i+1] < cost[i+1]呢? 此时表示我们刚才遍历过的所有位置,都是没办法满足条件的。 我们直接将初始值设置为i+2,油箱清零,继续计算即可。这样只需要O(n)的时间复杂度即可完成解题。
class Solution:
def canCompleteCircuit(self, gas, cost):
if sum(gas) < sum(cost):
return -1
ln = len(gas)
for i in range(ln):
if gas[i] < cost[i]:
continue
total = 0
for j in range(i, i + ln):
j %= ln
total += gas[j] - cost[j]
if total < 0:
break
else:
return i
return -1class Solution:
def canCompleteCircuit(self, gas, cost):
if sum(gas) < sum(cost):
return -1
total = start = 0
for i in range(len(gas)):
total += gas[i] - cost[i]
if total < 0:
total = 0
start = i + 1
return startclass Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int total_gas = 0;
for (int i = 0; i < gas.length; i++) {
total_gas += gas[i] - cost[i];
}
if (total_gas < 0) {
return -1;
}
int cnt = 0;
int start = 0;
for (int j = 0; j < gas.length; j++) {
cnt += gas[j] - cost[j];
if (cnt < 0) {
cnt = 0;
start = j + 1;
}
}
return start;
}
}欢迎关注我的公众号: 清风Python,带你每日学习Python算法刷题的同时,了解更多python小知识。
有喜欢力扣刷题的小伙伴可以加我微信(King_Uranus)互相鼓励,共同进步,一起玩转超级码力!
我的个人博客:https://qingfengpython.cn