zoukankan      html  css  js  c++  java
  • Gas Station leetcode 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.

    题解

     网上搜到的解法。

     据说是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];  
    10             total += gas[i]-cost[i];  
    11             if(sum < 0){  
    12                 index=i+1; 
    13                 sum = 0;   
    14             } 
    15         }  
    16         if(total<0)
    17             return -1;  
    18         else
    19             return index;  
    20     }

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

  • 相关阅读:
    eclipse快捷键
    iOS音频播放 (二):AudioSession 转
    HNU13377:Book Club(DFS)
    BAPC2014 K&amp;&amp;HUNNU11591:Key to Knowledge(中途相遇法)
    小米净水器与小区过滤价格水对照.xls
    NUTCH2.3 hadoop2.7.1 hbase1.0.1.1 solr5.2.1部署(一)
    hibernate动态表名映射--仅仅有想不到,没有做不到
    【BZOJ 1660】 [Usaco2006 Nov]Bad Hair Day 乱发节
    oracle-企业信息化
    线性查找算法
  • 原文地址:https://www.cnblogs.com/springfor/p/3888036.html
Copyright © 2011-2022 走看看