贪心
import java.util.Arrays;
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
/**
* 如果总的油量小于总的消耗量,那肯定无法跑一圈
*/
if (Arrays.stream(gas).sum() - Arrays.stream(cost).sum() < 0){
return -1;
}
int n = gas.length;
int start = 0;
int sum = 0;
/**
* 从第一个加油站开始跑,每到一个加油站就统计总的剩余油量
* 如果大于等于0那就可以接着跑
* 如果小于0说明当前选的起始位置不对,将下一个加油站设置为新的起始点,重置循环次数和总的剩余油量
* 因为这个循环是环形的,所以要用while循环,当到达最后一个加油站,下一个要手动设置为第一个
*/
while (n >= 0){
if (start == gas.length){
start = 0;
}
sum += gas[start] - cost[start];
if (sum >= 0){
start++;
n--;
}
else {
start++;
n = gas.length;
sum = 0;
}
}
/**
* 当完整的跑完一圈以后,start会停在起点的下一个位置
*/
return start - 1;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(1)
*/
优化1——同步计算总差值
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int start = 0;
int sum = 0;
int totalSum = 0;
/**
* 直接在循环中用totalSum统计总的油量和消耗量的差
* 如果当前位置的油量sum小于0,就将起点设置为下一个
* 环形数组的索引需要对长度取余
*/
for (int i = 0; i < gas.length; i++) {
sum += gas[i] - cost[i];
totalSum += gas[i] - cost[i];
if (sum < 0){
sum = 0;
start = (i + 1) % gas.length;
}
}
/**
* 如果totalSum小于0,肯定不能跑一圈
*/
if (totalSum < 0){
return -1;
}
return start;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(1)
*/
https://leetcode-cn.com/problems/gas-station/