美文网首页
Leetcode经典问题全面解析

Leetcode经典问题全面解析

作者: Catcher07 | 来源:发表于2018-07-22 15:17 被阅读0次

134题 环形公路加油站

原题地址
https://leetcode.com/problems/gas-station/description/

  1. 题解
class Solution:
    def canCompleteCircuit(self, gas, cost):
        """
        :type gas: List[int]
        :type cost: List[int]
        :rtype: int
        """
        start, remain_gas, total = 0, 0, 0
        for i in range(len(gas)):
            total += gas[i] - cost[i]
            if remain_gas < 0:
                start = i
                remain_gas = gas[i] - cost[i]
            else:
                remain_gas += gas[i] - cost[i]
        return start if total >= 0 else -1
  1. 题解
class Solution_2 {
  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];
            }
        }
        return sum >= 0 ? start : -1;
    }
};

相关文章

网友评论

      本文标题:Leetcode经典问题全面解析

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