leetcode刷题系列C++-Gas Station
来源:互联网 发布:mysql语句sql union 编辑:程序博客网 时间:2024/06/01 10:33
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.
Subscribe to see which companies asked this question
class Solution {public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { const int length = gas.size(); int sum = 0; int total = 0; int j = -1; for(int i = 0; i < length; ++i) { sum += gas[i] - cost[i]; total += gas[i] - cost[i]; if(sum < 0) { j = i ; sum = 0; } } if(total < 0) { return -1; } else { return j + 1; } }};题目详解:
1.total值是用来记录整个能量圈的正负,如果整个圈都是负值,那么怎么跑都不可能跑完
2.sum值是用来记录里面局部的能量正负,局部可能会gas特别多可以用于下一段,也可能缺失,直接跳到下一个点进行。
总之,只要能量圈的总值是正的,那么就肯定能跑完有解。
0 0
- leetcode刷题系列C++-Gas Station
- [leetcode刷题系列]Gas Station
- [C++]LeetCode: 119 Gas Station
- LeetCode刷题笔录Gas Station
- 开始刷题leetcode day5: Gas Station
- leetcode 刷题之路 68 Gas Station
- LeetCode:Gas Station
- [LeetCode] Gas Station
- [leetcode]Gas Station
- Leetcode: Gas Station
- LeetCode:Gas Station
- [LeetCode] Gas Station
- leetcode Gas Station
- [LeetCode]Gas Station
- LeetCode 之 Gas Station
- leetcode Gas Station
- 【Leetcode】Gas Station
- LeetCode | Gas Station
- spring-jdbc文件数据库配置加密
- ubuntu下配置tomcat服务器
- 10003---Linux中的ls命令详细使用
- Android UI效果之绘图篇(二):Canvas
- 解决“Dynamic Web Module 3.0 requires Java 1.6 or newer.”错误
- leetcode刷题系列C++-Gas Station
- `GLIBCXX_3.4.15' not found
- POJ 3984 迷宫问题(BFS+路径输出)
- 网站502与504错误分析
- 使用Google Guava实现定时缓存功能
- eclipse中将项目发布到tomcat的root目录
- java日志概述和原理
- Cocoapods系列教程(一)——入门
- OC 在任意页面,隐藏其他页面的键盘