134. Gas Station-贪心算法

来源:互联网 发布:神漫画软件下载 编辑:程序博客网 时间:2024/05/01 02:35
原题链接:134. Gas Station

【思路1】

从末站开始,startStation和endStation均指向最后一站,一旦发现剩余的油量小于0,那么startStation前移——回去“加油”,直到油量大于等于0,那么endStation开始后移——继续前进。如果最后的剩余油量大于等于0,那么表示可以环游一周,startStation即为解。否则,不可以,返回 -1。

public class Solution {    public int canCompleteCircuit(int[] gas, int[] cost) {        int start = gas.length - 1, location = 0;        int remain = gas[start] - cost[start];  //起点假设为数组的最后一个位置        while(location < start) {  //当 location>=start 时,说明已考察完一圈了,不再继续            if (remain < 0) remain += gas[--start] - cost[start];  //油量不足,原先的 start 不适合作为起点,起点前移            else remain += gas[location] - cost[location++];  //油量充足,这个 start 可能是适合的起点,继续前进        }        return remain >= 0 ? start : -1;  //如果油量大于等于0,那么说明已经成功游历完一圈    }}

16 / 16 test cases passed. Runtime: 1 ms  Your runtime beats 7.59% of javasubmissions.
【思路2】

假设startStation = 0,往后开,假设在第 i 站第一次总油量小于0,那么表示 0 至第 i - 1 站均不适合作为起始站,此时总剩余油量 remain1 < 0。那么将第 i 站作为起始站,同样的,一旦发现油量 remain2 < 0,那么就重设起始站。最后遍历完gas之后,如果 totalRemain >= 0,那么startStation就是起始站,并且[startStation, gas.length - 1]必然remain均大于0:

    public int canCompleteCircuit(int[] gas, int[] cost) {        int startStation = 0, totalRemain = 0, remain = 0;        for (int i = 0; i < gas.length; i++) {            totalRemain += gas[i] - cost[i];            if (remain < 0) {                remain = gas[i] - cost[i];                startStation = i;            } else {                remain += gas[i] - cost[i];            }        }        return totalRemain >= 0 ? startStation : -1;    }
欢迎优化!

1 0
原创粉丝点击