LeetCode 134. 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.

算法分析
一道很简洁感觉很可爱的小题目www
不知道该归为什么算法,解法很巧妙,时间复杂度O(n),以及O(1)的额外空间。
其实只要gas的和大于cost的和,就一定能找到一个起点了,所以主要需要解决的是如何找到这个起点。
由于路径是个环,为了方便编写代码,首先将起点设到数组的最后一个位置,结尾则是起点的下一个位置(数组的第一个位置,因为是环)。用sum累计从start到end前一位置的剩余油量,之后每次循环若sum<0则将start前移,sum>=0则end后移。start和end重合时退出循环,若能够完成旅行start所在位置则为起点。

具体实现

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int start = gas.size()-1;
        int 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];
            }
        }
        if (sum >= 0) return start;
        else return -1;
    }
};

提交结果

16 / 16 test cases passed.
Status: Accepted
Runtime: 6 ms
Submitted: 29 minutes ago
Your runtime beats 17.78 % of cpp submissions.

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值