[LeetCode 题解]:Gas Station
2014-05-22 22:38
281 查看
前言
【LeetCode 题解】系列传送门: http://www.cnblogs.com/double-win/category/573499.html
1.题目描述
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 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.
2. 思路
题解: 与经典的最大字段和问题类似,采用贪心策略。3. 解法
1 class Solution { 2 public: 3 int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { 4 int station = gas.size(); 5 int i,sum=0,start=0,total=0; 6 7 for(i=0;i<station;i++) 8 gas[i]-=cost[i]; 9 10 for(i=0;i<station;i++) total+=gas[i]; 11 if(total<0) return -1; 12 13 // 与求最大子段和类似,使用贪心策略 14 for(i=0;i<station;i++) 15 { 16 sum+= gas[i]; 17 if(sum<0) 18 { 19 start=i+1; // 如果当前和为负数,选择下一个元素作为起点 20 sum=0; 21 } 22 } 23 return start; 24 } 25 };
4. 相关题目
Maximum Subarray : /article/5296479.html![]() | 作者:Double_Win 出处: /article/5296478.html 声明: 由于本人水平有限,文章在表述和代码方面如有不妥之处,欢迎批评指正~ |
相关文章推荐
- LeetCode(16)题解--3Sum Closest
- [LeetCode]题解(python):059-Spiral Matrix II
- LeetCode题解 第十五周
- 【LeetCode题解】19_删除链表的倒数第N个节点(Remove-Nth-Node-From-End-of-List)
- [Leetcode题解]002 Add Two Numbers
- leetcode题解-45. Jump Game II
- leetcode题解-483. Smallest Good Base
- 【题解】【排列组合】【回溯】【Leetcode】Generate Parentheses
- LeetCode题解:Populating Next Right Pointers in Each Node
- LeetCode110.Balanced Binary Tree题解
- Leetcode题解(二)
- LeetCode题解系列--712. Minimum ASCII Delete Sum for Two Strings
- LeetCode题解 #3 Longest Substring Without Repeating Characters
- leetcode_效率题解_148. Sort List_(链表归并排序)
- leetcode题解-29. Divide Two Integers
- LeetCode题解:Max Consecutive Ones
- [LeetCode]题解(python):117-Populating Next Right Pointers in Each Node II
- LeetCode题解 #7 Reverse Integer
- [LeetCode]题解(python):121-Best Time to Buy and Sell Stock
- LeetCode题解-206-Reverse Linked List Ⅰ