gas-station leetcode C++
2024-09-06 15:00:02
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.
C++
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int total = 0, sum = 0;
int index = -1;
for (int i = 0; i < gas.size(); i++) {
sum += gas[i] - cost[i];
total += gas[i] - cost[i];
if (sum < 0) {
sum = 0;
index = i;
}
}
return total >= 0 ? index + 1 : -1;
}
};
最新文章
- linux 如何对文件解压或打包压缩
- 【转】 iOS9.2-iOS9.3.3越狱插件清单
- 《zw版&#183;Halcon入门教程与内置demo》
- Java文件读取
- 为什么玩VR眼镜会头晕?
- 熟练使用git命令
- lightoj1027
- HDFS Java API 常用操作
- 【PHP】iOS推送通知以及反馈服务
- CREATE PROCEDURE
- 基于visual Studio2013解决C语言竞赛题之0202坐标转换
- RPC框架
- Ubuntu下OpenVPN客户端配置教程
- 向量相加CUDA练习
- AJAX封装(IE)
- 浅析ConcurrentHashMap
- Activiti获取ProcessEngine的三种方法
- 关于Android中ION的libion
- 转载:删除github上文件夹的两种方式
- HTTP 请求头中的 X-Forwarded-For,X-Real-IP