题解 | #加油站#

加油站

https://www.nowcoder.com/practice/a013a0691a0343aeb262ca1450d2fe4e

  • 刚开始尝试第一个开始(下标为0),last标记当前剩余油量
  • 当l再次回到0的时候,表明没有方案,返回-1
  • 当r == l的时候,表明有方案,返回l
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param gas int整型一维数组 
     * @param cost int整型一维数组 
     * @return int整型
     */
    public int gasStation (int[] gas, int[] cost) {
        int l = 0, r = 1;
        int last = gas[0] - cost[0];
        while (true) {
            while (last < 0 && l != r) {
                last = last - gas[l] + cost[l];
                l = (l + 1) % cost.length;
                if (l == 0) {
                    return -1;
                }
            }
            last = last + gas[r] - cost[r];
            r = (r + 1) % cost.length;
            if (r == l) {
                return l;
            }
        }
    }
}
全部评论

相关推荐

起名字真难233:人家只有找猴子的预算,来个齐天大圣他们驾驭不住呀😂😂
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务