leetcode: Gas Station

来源:互联网 发布:及时生成字幕软件 编辑:程序博客网 时间:2024/06/02 07:05

两重循环....

public class Solution {    public int canCompleteCircuit(int[] gas, int[] cost) {        int gasNum = gas.length;        if(gasNum<1)        {            return 0;        }        for(int i=0;i<gasNum;i++)        {            int gasAll = 0;            int st=i;            int end;            if(st==0)            {                end = gasNum-1;                int flag=0;                for(int j=st;j<=end;j++)                {                    gasAll += gas[j]-cost[j];                    if(gasAll<0)                    {                        flag=1;                        break;                    }                }                if(flag==0)                {                    return st;                }            }            else            {                int flag=0;                end = st-1;                for(int j=st;j<=gasNum-1;j++)                {                    gasAll += gas[j]-cost[j];                    if(gasAll<0)                    {                        flag=1;                        break;                    }                }                for(int j=0;j<=st-1;j++)                {                    gasAll += gas[j]-cost[j];                    if(gasAll<0)                    {                        flag=1;                        break;                    }                }                if(flag==0)                {                    return st;                }            }        }        return -1;    }}


0 0
原创粉丝点击