java 134.加油站(#)。java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 134.加油站(#)。java相关的知识,希望对你有一定的参考价值。

class Solution {
public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {

       int start = gas.size()-1;
       int end = 0;
       int sum = gas[start] - cost[start];
       while (start > end) {
          if (sum >= 0) {
             sum += gas[end] - cost[end];
             ++end;
          }
          else {
             --start;
             sum += gas[start] - cost[start];
          }
       }
       return sum >= 0 ? start : -1;
    }
};
public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int start = 0, total = 0, tank = 0;
        for (int i = 0; i < gas.length; i++) {
            if ((tank = tank + gas[i] - cost[i]) < 0) {
                start = i + 1;
                total += tank;
                tank = 0;
            }
        }
        return total + tank < 0 ? -1 : start;
    }
}
/*
[4]
[5]
[1,2,3,4,5]
[2,5,1,2,1]
[1,2]
[2,1]
*/
public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        if  (gas == null || cost == null || gas.length < 1 || cost.length < 1) return -1;
        int len = gas.length;
        int[] left = new int[len];
        int sum = 0;
        for (int i = 0; i < len; i++) {
            left[i] = gas[i] - cost[i];
            sum += left[i];
        }
        if (sum < 0) return -1;
        int curLeft = 0;
        int res = 0;
        for (int i = 0; i < len; i++) {
            curLeft += left[i];
            if (curLeft < 0) {
                res = i + 1;
                curLeft = 0;
            } 
        }
        return res;
    }
}

以上是关于java 134.加油站(#)。java的主要内容,如果未能解决你的问题,请参考以下文章

java 134.加油站(#)。java

java 134.加油站(#)。java

java 134.加油站(#)。java

java 134.加油站(#)。java

java 134.加油站(#)。java

java 134.加油站(#)。java