【LeetCode Daily Question】[Moderate]134. Gas Station
134. Gas Station
Algorithm idea: array
topic:
java code-brute force
Violence, enumerate every position, and judge it can travel for a week
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
//暴力,枚举每一个位置,判断能都行驶一周
int n = gas.length;
for (int i = 0; i < n; i++) {
//遍历每一个位置
int oilMass = 0;
int j = i;
while (oilMass >= 0) {
//判断当前位置能否行驶一周
oilMass = oilMass + gas[j] - cost[j];
j = (j + 1) % n;
if (oilMass >= 0 && j == i) {
//如果可以则返回i
return i;
}
}
}
return -1;//不能行驶一周
}
}
java code-traverse it again
Using, x can reach y and any station before y, but cannot reach the next station of y, then any station in the interval (x,y) cannot reach the next station of y;
explain:
- Suppose there is x'which is one of the stations [x,y];
- x can reach each station from x to y, then the sum of [x, x'] and the sum of [x, y] must be >=0,
- x cannot reach the next stop of y, then the sum of [x, y+1] is superimposed and <0;
- It can be seen that [x,y+1]-[x, x'] = [x', y+1] <0;
- Therefore, any station in the [x,y] interval cannot reach the next station of y; (x can be directly jumped to y+1 when traversing, and the middle station does not need to be considered)
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
//遍历一遍,O(n)
//利用,x不能到y的下一站,则[x,y]区间内的任意一站无法到达y的下一站
int n = gas.length;
int i = 0;
while (i < n) {
int oilMass = 0;
int j = i;
int count = 0;//用来计数,是否行驶了一周
//寻找 i 最大能到达的站 y
while (oilMass >= 0 && count < n) {
//判断当前位置能否行驶一周
oilMass = oilMass + gas[j] - cost[j];
j = (j + 1) % n;
count++;
if (oilMass >= 0 && count == n) {
//如果行驶了一周,返回i
return i;
}
}
i = i + count;//如果不能行驶一周,i 直接移动到 y 的下一站
}
return -1;//不能行驶一周
}
}
java code
Use, as shown in the figure below, to analyze the
main function of the source code: find the lowest point of the black line in the figure; if the sum is >=0, the starting point is the next position of the lowest point; if the sum is <0, there is no solution
class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int n = gas.length;
int totalGas = 0;//总和
int minGas = Integer.MAX_VALUE;
int mindx = 0;
for (int i = 0; i < n; i++) {
totalGas += gas[i] - cost[i];
if (totalGas < minGas) {
//寻找最低点,记录下标
minGas = totalGas;
mindx = i;
}
}
return totalGas >= 0 ? (mindx + 1) % n : -1;
}
}