134. Gas Station
来源:互联网 发布:客厅电脑主机 知乎 编辑:程序博客网 时间:2024/06/07 01:19
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.
题意:加油,每个站点可加gas[i],每个站点要消耗cost[i],问能否环一周。
思路:暴力的解法是从每个点开始,进行环游一周,记录各个点的油量,然后看油量是否满足消耗。不满足则说明这个点开始不行。如果所有点都进行完了,则结果能不能环游一周也就知道了。第二种思路是,用一个全局的变量记录总的油耗对比,并用局部的sum记录结点间的油耗情况,如果有一个点过不去,则从下一个点开始进行。
class Solution {public:int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {int total = 0;int sum = 0;int index = 0;for (int i = 0; i < gas.size(); i++){sum += gas[i] - cost[i];total += gas[i] - cost[i];if (sum < 0){index = i + 1;sum = 0;}}return total >= 0 ? index : -1;}};
0 0
- [LeetCode]134.Gas Station
- LeetCode 134. Gas Station
- [Leetcode] 134. Gas Station
- 134. Gas Station
- [leetcode] 134. Gas Station
- Leetcode-134.Gas Station
- 134. Gas Station LeetCode
- 134. Gas Station
- Leetcode 134. Gas Station
- 134. Gas Station
- 134. Gas Station
- [LeetCode]134. Gas Station
- LeetCode 134. Gas Station
- leetcode 134. Gas Station
- LeetCode *** 134. Gas Station
- 134. Gas Station
- LeetCode 134. Gas Station
- 【LeetCode】134. Gas Station
- mysql二进制日志
- webmagic的设计机制及原理-如何开发一个Java爬虫
- Android开源代码汇总
- jQuery函数的第二个参数获取指定上下文中的DOM元素
- Eclipse快捷键和10个最有用的快捷键
- 134. Gas Station
- caffe源码阅读笔记(1):路线图
- 第四专题 Problem J
- 欢迎使用CSDN-markdown编辑器
- i2c驱动程序
- SpringBoot入门系列:第七篇 Spring Boot的测试
- phpmyadmin取消最大文件限制的更改解决方法
- git常用命令整理
- [Linux] NFSv4 and Autofs caveats