美文网首页
LeetCode算法系列(二)

LeetCode算法系列(二)

作者: hopestar90 | 来源:发表于2017-02-23 17:12 被阅读44次

一 前言

    昨天开始了算法系列的第一篇,是有关树的一个问题,今天给大家继续带来有关贪心策略的一个问题~现在就开始吧~

二 题目

There are N gas stations along a circular route, where the amount of gas at station i isgas[i].
You have a car with an unlimited gas tank and it costscost[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.

题目的大致意思就是:有一个由N个加油站组成的环形路径,第i个加油站储存了gas[i]这么多的汽油,你最开始有一个没有汽油的坦克,你从第i个加油站走到它的下一个i+1个加油站消耗汽油cost[i]这么多,问你是否可以找到一个站,从该站出发可以绕着该路径兜风一圈,有的话返回该站的标号,没有的话返回-1。

三 思路分析及代码

我们假设坦克从N-1这站出发(也就是0后面那个,因为他们是个环形所以首尾相接),末尾位置我们设为0,也就是start = N-1,end = 0,从start开始往end的方向走,这个时候我们设置一个变量sum用来记录坦克油箱中还剩多少油。那么开始时sum = gas[i] - cost[i],接下来是关键,如果现在这个sum大于0证明坦克现在还有油,就可以尝试向下一站走,也就是end++。如果sum小于0证明坦克从start开往他的下一站(针对当前状态就是从N-1开到0)没有足够的油了,那么就尝试把start往前一站挪,也就是变为从N-2开始尝试。不断进行这样的操作,知道start <= end证明真个过程结束了,这时如果sum >= 0证明可以支撑坦克走完一圈,返回对应的start位置就是结果。如果sum < 0证明坦克无法走完一圈,返回-1。分析完毕,我们上代码:

public:
    int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
        int start = lens-1, end = 0;
        int sum = gas[start] - cost[start];
        while(start>end){
            if(sum>=0){
                sum += gas[end] - cost[end];
                ++end;
            }
            else{
                --start;
                sum += gas[start] - cost[start];
            }
        }
        return sum >=0 ? start: -1;
    }
};

四 后记

期待我们的下一个题目吧

相关文章

  • Search Insert Position

    标签: C++ 算法 LeetCode 数组 二分查找 每日算法——leetcode系列 问题 SeSearch...

  • Search for a Range

    标签: C++ 算法 LeetCode 数组 二分查找 每日算法——leetcode系列 问题 Search f...

  • Search in Rotated Sorted Array

    标签: C++ 算法 LeetCode 数组 困难 二分法 每日算法——leetcode系列 问题 Search...

  • Swap Nodes in Pairs

    标签: C++ 算法 LeetCode 链表 每日算法——leetcode系列 问题 Swap Nodes in ...

  • Combination Sum II

    标签: C++ 算法 LeetCode DFS 每日算法——leetcode系列 问题 Combinatio...

  • Divide Two Integers

    标签: C++ 算法 LeetCode 每日算法——leetcode系列 问题 Divide Two Integ...

  • First Missing Positive

    标签: C++ 算法 LeetCode 数组 每日算法——leetcode系列 问题 First Missing...

  • Valid Sudoku

    Valid Sudoku 标签: C++ 算法 LeetCode 每日算法——leetcode系列 问题 Val...

  • Next Permutation

    标签: C++ 算法 LeetCode 数组 每日算法——leetcode系列 问题 Next Permuta...

  • Trapping Rain Water

    标签: C++ 算法 LeetCode 数组 每日算法——leetcode系列 问题 Trapping Rain...

网友评论

      本文标题:LeetCode算法系列(二)

      本文链接:https://www.haomeiwen.com/subject/ddumwttx.html