zoukankan      html  css  js  c++  java
  • LeetCode——Gas Station

    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.

    原题链接:https://oj.leetcode.com/problems/gas-station/

    题目:在一个环上有N个加油站。站 i 有 gas[i] 的油。

    你有一辆汽车有无限大小的油箱,它从站 i 到站 i+1 要耗cost[i] 的油。你以空油箱从当中的一个站出发。

    假设你转了一圈,返回起始油站的索引,否则返回-1.

    思路:先计算车到达每一个加油站时加油站的油量和汽车消耗的油量之差。假设之差小于0,则说明汽车至少要从下一站出发。由于从本站出发的话。就到达不了下一站。假设总的之差小于0,则车无法完毕一圈。

    	public int canCompleteCircuit(int[] gas, int[] cost) {
    		int minus = 0, total = 0, index = -1;
    		for (int i = 0; i < gas.length; i++) {
    			minus += gas[i] - cost[i];
    			total += minus;
    			if (minus < 0) {
    				index = i;
    				minus = 0;
    			}
    		}
    		return total < 0 ?

    -1 : index + 1; }



  • 相关阅读:
    C#解压或压缩文件夹
    C#文件帮助类FoderHelper
    C#数据库帮助类SqlHelper
    非常有意思的程序猿数据比較
    hdu1066
    【SICP练习】149 练习4.5
    【spring+websocket的使用】
    Android Studio 使用正式签名进行调试
    基于空间直方图meanshift跟踪
    Intel为Google的物联网平台Brillo推出开发板Edison
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/6801305.html
Copyright © 2011-2022 走看看