Gas Station (leetcode)
来源:互联网 发布:成都数控编程学徒招聘 编辑:程序博客网 时间:2024/05/29 15:18
题目:
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.
题目来源:https://oj.leetcode.com/problems/gas-station/
解题思路:从gas[i]>cost[i]的汽油站开始,保证车内加的油要大于消耗的油即可,如果不满足,则从不满足的值k的下一个k+1开始接着寻找这个能满足的i,直到最后。《leetcode题解》中的代码更短,思路也更清晰。
#include<iostream>#include<vector>using namespace std;int canCompleteCircuit(vector<int> &gas, vector<int> &cost){if(gas.empty())return 0;for(int i=0;i<gas.size();i++){if(gas[i]>=cost[i]){int j=0,sumGas=0,sumCost=0;bool flag=true;for(j=i;j<gas.size();j++){sumGas+=gas[j];sumCost+=cost[j];if(sumGas<sumCost){i=j;flag=false;break;}}j=gas.size()-1;if(flag==true){for(j=0;j<i;j++){sumGas+=gas[j];sumCost+=cost[j];if(sumGas<sumCost)return -1;}if(i==j)return i;}}}return -1;}int main(){const int N=1;int A[]={2};int B[]={2};vector<int> gas(A,A+N);vector<int> cost(B,B+N);int result=canCompleteCircuit(gas,cost);system("pause");return 0;}
0 0
- 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
- LeetCode之Gas Station
- Leetcode: Gas Station
- LeetCode OJ:Gas Station
- [LeetCode]134.Gas Station
- [Leetcode] Gas Station (Java)
- gas station leetcode
- Hbase 笔记(11) 性能优化
- Basic脚本解释器移植到STM32
- struts2中的web.xml配置
- 解决linux系统CentOS下调整home和根分区大小
- Linux/Unix系统镜像/备份/恢复
- Gas Station (leetcode)
- python 二叉树
- 《深入理解计算机系统》之Unix I/O函数
- SFDC
- mktime
- iOS Core Animation 简明系列教程
- jquery textarea值的更新与获取 text() vs val()
- Object-C Category和Extension的区别
- Hbase 笔记(12) 集群管理