leetCode练习(1)

题目:gas station

难度:MEDIUM

问题描述:

There are N gas stations along a circular route, where the amount of gas at station i is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1.

Note:

  • If there exists a solution, it is guaranteed to be unique.
  • Both input arrays are non-empty and have the same length.
  • Each element in the input arrays is a non-negative integer.

Example 1:

Input: 
gas  = [1,2,3,4,5]
cost = [3,4,5,1,2]

Output: 3

Explanation:
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.

Example 2:

Input: 
gas  = [2,3,4]
cost = [3,4,3]

Output: -1

Explanation:
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.

求解思路:

/*
  * gas是加油站,是环形。从i到i+1,消耗cost[i]
  * 求一个出发点,使得能完整跑一圈
  * A-B-...-C
  * 如果C是第一个A不能到达的地方
  * 有:sum(gas[B-C]+gas[A]<cost[B-C]+cost[A])
  * 此外,有A一定能到B,有 gas[A]>=cost[A]
  * 两者有
  * 结论1:gas[B-C]<cost[B-C] => A到C之间的点一样不能到C
  * 此外有
  * 结论2:如果sum[gas]>=sum[cost] => 一定有解
  */

代码如下:

int len;
 public int canCompleteCircuit(int[] gas, int[] cost) {
  int gsum = 0;
  for(int w : gas) gsum+=w;
  int csum = 0;
  for(int w : cost) csum+=w;
  if(gsum<csum) return -1;//花费总量大于资源总量
  len = gas.length;
  
  int start = 0;
  int tail = 0;
  int g = 0;
  int c = 0;
  int size = 0;
  while(size<len){
   size++;
   g += gas[tail];
   c += cost[tail];
   tail = nextIndex(tail);
   if(g<c){//start不能到tail
    start = tail;
    g=0;
    c=0;
    tail = start;
    size = 0;
    continue;
   }
  }
  return start;
    }
 private int nextIndex(int nowIndex){
  if(nowIndex == len-1) return 0;
  else return nowIndex+1;
 }


猜你喜欢

转载自blog.csdn.net/u010771890/article/details/80584564