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.

    解题思路:

    如果所有花费的汽油之和>所有站点可提供的汽油之和,无解, return -1,这里用gap变量记录该差值,并且用sum变量记录当前差值,如果差值小于0,将当前站点设为index,sum设为0。

     1 class Solution {
     2 public:
     3     int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
     4         int gap = 0;
     5         int sum = 0;
     6         int index = -1;
     7         for (int i = 0; i < gas.size(); ++i) {
     8             gap += gas[i] - cost[i];
     9             sum += gas[i] - cost[i];
    10             if (sum < 0) {
    11                 index = i;
    12                 sum = 0;
    13             }
    14         }
    15         
    16         if (gap >= 0) {
    17             return index + 1;
    18         }
    19         
    20         return -1;
    21     }
    22 };
  • 相关阅读:
    iOS开发---iPhone SDK 包含哪些东西?
    COS-8文件系统
    COS-7设备管理
    COS-6主存管理
    COS-5资源分配与调度
    COS-4进程及进程管理
    饭卡管理系统学生E-R图
    COS-3OS的用户接口
    COS-2OS结构和硬件支持
    计算机操作系统-1绪论
  • 原文地址:https://www.cnblogs.com/skycore/p/4888508.html
Copyright © 2011-2022 走看看