[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 };
复制代码

 

posted @   skycore  阅读(133)  评论(0编辑  收藏  举报
编辑推荐:
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
阅读排行:
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· 一个基于 .NET 开源免费的异地组网和内网穿透工具
· 《HelloGitHub》第 108 期
· Windows桌面应用自动更新解决方案SharpUpdater5发布
· 我的家庭实验室服务器集群硬件清单
历史上的今天:
2014-10-17 [LeetCode]Add Two Numbers
点击右上角即可分享
微信分享提示