当前位置:   article > 正文

算法 --- leetcode之gas-station_leetcode gas station

leetcode gas station

题目描述:

环形路上有n个加油站,第i个加油站的汽油量是gas[i].

你有一辆车,车的油箱可以无限装汽油。从加油站i走到下一个加油站(i+1)花费的油量是cost[i],你从一个加油站出发,刚开始的时候油箱里面没有汽油。

求从哪个加油站出发可以在环形路上走一圈。返回加油站的下标,如果没有答案的话返回-1。

注意:

答案保证唯一。

解题思路(转):

从start出发, 如果油量足够, 可以一直向后走 end++;  油量不够的时候,start向后退  最终 start == end的时候,如果有解一定是当前 start所在位置

Java源码实现(转):

  1. public class Solution {
  2. public int canCompleteCircuit(int[] gas, int[] cost) {
  3. int start = gas.length - 1;
  4. int end = 0;
  5. int sum = gas[start] - cost[start];
  6. while(start > end){
  7. if(sum >= 0){
  8. sum += gas[end] - cost[end];
  9. ++end;
  10. }else{
  11. --start;
  12. sum += gas[start] - cost[start];
  13. }
  14. }
  15. return sum >=0 ? start : -1;
  16. }
  17. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/493498
推荐阅读
相关标签
  

闽ICP备14008679号