码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Gas Station 题解

时间:2014-05-26 13:25:00      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:style   c   class   blog   code   java   

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.

 

题解: 与经典的最大字段和问题类似,采用贪心策略。

bubuko.com,布布扣
 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 };
bubuko.com,布布扣

类似一题: Maximum Subarray : http://www.cnblogs.com/double-win/p/3746672.html

LeetCode:Gas Station 题解,布布扣,bubuko.com

LeetCode:Gas Station 题解

标签:style   c   class   blog   code   java   

原文地址:http://www.cnblogs.com/double-win/p/3746637.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!