zoukankan      html  css  js  c++  java
  • LeetCode——Gas Station

    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, otherwise return -1.

    Note:
    The solution is guaranteed to be unique.

    贪心or动态规划?

    从gas[0]开始走,遇到油不够的情况,开始station就后退一步,利用以前算的结果可以只算出第一步的油量。直到最后,算出circle的连接点是否满足。

    public class Solution {
        public int canCompleteCircuit(int[] gas, int[] cost) {
            
            int n = gas.length;
            
            int start = 0, end = 0, have = 0, cur = 0;
            
            for(int i=0; i<n-1; i++) {
                have += gas[cur] - cost[cur];
                if(have >= 0) {
                    end ++;
                    cur = end;
                }
                else {
                    start --;
                    if(start < 0) {
                        start = n - 1;
                    }
                    cur = start;
                }
            }
            
            have += gas[cur] - cost[cur];
            
            return have>=0?start:-1;
        }
    }
  • 相关阅读:
    Simple ASP.NET CORE 2.2 App +Vue JS
    Upload Image to .NET Core 2.1 API
    Nginx支持WebSocket服务
    DD打卡
    Asp.net Core 源码-PagedList<T>
    Asp.net Core 源码-UrlExtensions
    Asp.net Core 源码-SessionExtensions
    树莓派资源集合
    frp内网穿透
    Nuget包含cssjs等资源文件
  • 原文地址:https://www.cnblogs.com/wxisme/p/4881628.html
Copyright © 2011-2022 走看看