加油站

题目描述:在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。

你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。

如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。

说明:

  • 如果题目有解,该答案即为唯一答案。
  • 输入数组均为非空数组,且长度相同。
  • 输入数组中的元素均为非负数。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/gas-station/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:穷举法

从第一个加油站开始,判断从当前加油站开始作为起点是否可以环行一周回到起点,如果可以,则返回当前加油站的位置,如果不可以则将下一个加油站作为起点判断。具体判断某一个加油站作为起点是否可以环行的过程如下:

  • 如果当前油量加上当前加油站的汽油量少于当前加油站的消耗,说明无法走到下一站,跳过这种可能性;
  • 如果可以走到下一站,记录当前剩余油量和已经走过的加油站的数量,然后走到下一站,继续判断;
  • 知道走到最后,如果走过所有加油站,说明以当前的起始加油站作为起点是可以环行一周的,返回起始加油站的位置。
  1. public class LeetCode_134 {
  2. /**
  3. * 穷举法
  4. *
  5. * @param gas
  6. * @param cost
  7. * @return
  8. */
  9. public static int canCompleteCircuit(int[] gas, int[] cost) {
  10. // 总共有n个加油站
  11. int totalN = gas.length;
  12. // 从第一个加油站开始遍历
  13. for (int i = 0; i < totalN; i++) {
  14. int gasCount = 0, startStation = i, runStationCount = 0;
  15. boolean flag = true;
  16. while (runStationCount < totalN) {
  17. // 如果当前油量加上当前加油站的汽油量少于当前加油站的消耗,说明无法走到下一站,跳过这种可能性
  18. if (gasCount + gas[startStation] < cost[startStation]) {
  19. flag = false;
  20. break;
  21. } else {
  22. // 剩余油量等于当前油量加上当前加油站的汽油量减去当前加油站的消耗
  23. gasCount = gasCount + gas[startStation] - cost[startStation];
  24. // 走过的加油站
  25. runStationCount++;
  26. // 下个加油站
  27. startStation++;
  28. if (startStation == totalN) {
  29. // 如果下个加油站等于n,从第一个加油站开始
  30. startStation = 0;
  31. }
  32. }
  33. }
  34. if (flag && runStationCount == totalN) {
  35. return i;
  36. }
  37. }
  38. return -1;
  39. }
  40. public static void main(String[] args) {
  41. int[] gas = new int[]{1, 2, 3, 4, 5};
  42. int[] cost = new int[]{3, 4, 5, 1, 2};
  43. System.out.println(canCompleteCircuit(gas, cost));
  44. }
  45. }

【每日寄语】 世上无难事,只怕有心人。一个人在实现理想的过程中,会遇到很多的困难,这不要紧,只要自己有那份心,坚持做下去,你就会成功。