• 134. Gas Station java solutions


    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.

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

    参考思路:

    http://www.cnblogs.com/felixfang/p/3814463.html

  • 相关阅读:
    django url路由
    web 协议
    动画效果 each循环
    页面载入
    js 事件 事件委托
    jQuery 文档操作
    jQuery 标签操作 样式操作
    筛选器方法
    jQuery 介绍
    js操作属性 类操作 事件
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5638626.html
Copyright © 2020-2023  润新知