Gas Station(leetcode)
来源:互联网 发布:windows如何打开pages 编辑:程序博客网 时间:2024/06/16 12:03
题目:
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
- PHP使用FTP转移文件夹以及子文件夹
- 视频编码器评估与参数优化
- 使用swig实现C++的python扩展功能
- POJ 1088滑雪 (记忆化DP)题解
- PHP获取指定日期所在月的第一天和最后一天
- Gas Station(leetcode)
- php导入excel表格生成数组
- 再谈 X-UA-Compatible 兼容模式
- 《与曹仁超对话》——MILK
- 直接拿来用!最火的Android开源项目(一)
- OSGi 和 Spring,第 1 部分: 使用 Apache Felix 构建和部署 OSGi 包
- Servlet技术开发
- 第五章--基本概念
- php 编码规范