题目

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.

题解

网上搜到的解法。

据说是Bloomberg的面试题。

用两个变量存+= gas[i] - cost[i]。一个帮助判断当前这个点作为gas station的起点合不合适,一个帮助判断总的需求是不是大于供给。如果总的需求大于供给那么肯定是无解的,如果需求小于等于供给,就可以返回刚才找到的起始点。

代码如下:

 1     public int canCompleteCircuit(int[] gas, int[] cost) {
 2         if (gas==null|| cost==null||gas.length==0||cost.length==0||gas.length!=cost.length)
 3          return -1;
 4          
 5         int sum = 0;  
 6         int total = 0;  
 7         int index = 0;  
 8         for(int i = 0; i < gas.length; i++){  
 9             sum += gas[i]-cost[i];  
             total += gas[i]-cost[i];  
             if(sum < 0){  
                 index=i+1; 
                 sum = 0;   
             } 
         }  
         if(total<0)
             return -1;  
         else
             return index;  
     }

Reference:http://blog.csdn.net/lbyxiafei/article/details/12183461

最新文章

  1. C# Memcache分布式缓存简单入门
  2. 解决windows 2003 无法安装vss2005的问题
  3. 1282 - Leading and Trailing ---LightOj1282(快速幂 + 数学)
  4. 从问题看本质:socket到底是什么(问答式)? .
  5. 总结c++ primer中的notes
  6. Mac环境下装node.js,npm,express;(包括express command not found)
  7. bzoj4028
  8. GIT 版本控制命令学习
  9. Ubuntu火狐、Chromium等浏览器安装flash插件
  10. Git合并分支出现的冲突解决
  11. ios 视频拼接/合成
  12. Spring boot——logback 基础使用篇(一)
  13. VS2015企业版和专业版永久密匙
  14. Android自定义View(三、深入解析控件测量onMeasure)
  15. json.parseArray源码解析
  16. Python-Django学习
  17. java学习笔记(十):scanner输入
  18. Java 实现字符串的加密与解密
  19. uigetfile的用法(批量读取图片)
  20. jsp+Servlet+JavaBean+JDBC+MySQL项目增删改查

热门文章

  1. jvm 参数配置优化
  2. BZOJ3956: Count
  3. 【BZOJ-4408】神秘数 可持久化线段树
  4. TC SRM601
  5. 《Go语言实战》摘录:6.2 并发 - goroutine
  6. linux 内核crash 命令
  7. RxJS 简介:可观察对象、观察者与操作符
  8. 学一点 MYSQL 双机异地热备份—-MYSQL主从,主主备份原理及实践
  9. 使用Axure RP原型设计实践02,自定义部件以及熟悉与部件相关面板
  10. 使用EF Code First搭建一个简易ASP.NET MVC网站,允许数据库迁移