题目:牛客网

解题思路:

从每个元素遍历gas数组,例如0->gas.len-1,1->gas.len-1->1,2->gas.len-1->2...,在遍历的过程中若cost[j] > gas[j]+more,则从元素i无法走完环形路,如果在一次循环中满足条件即flag==true,则直接返回下标,否则进入下一个元素的循环。

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        for(int i = 0 ; i < gas.length; i++){
            int more = 0;
            boolean flag = true;
            for(int j = i ; j < gas.length; j++){
                if(cost[j] > gas[j]+more){
                    flag = false;
                    break;
                }
                else{
                    if(j == gas.length-1)
                        more =  more+ gas[j]-cost[j];
                    else
                        more = more + gas[j]-cost[j];
                }
            }
            for(int j = 0 ; j < i ; j++){
                if(flag == false){
                    break;
                }
                if(cost[j] > gas[j]+more){
                    flag = false;
                    break;
                }
                else{
                    if(j == gas.length-1)
                        more =  more+ gas[j]-cost[j];
                    else
                        more = more + gas[j]-cost[j];
                }
            }
            if(flag == true){
                return i;
            }
            else{
                continue;
            }
        }
        return -1;
    }
}