zoukankan      html  css  js  c++  java
  • 加油站

    题目:

    环形路上有n个加油站,第i个加油站的汽油量是gas[i].
    你有一辆车,车的油箱可以无限装汽油。从加油站i走到下一个加油站(i+1)花费的油量是cost[i],你从一个加油站出发,刚开始的时候油箱里面没有汽油。
    求从哪个加油站出发可以在环形路上走一圈。返回加油站的下标,如果没有答案的话返回-1。
    注意:
    答案保证唯一。

    示例:

    输入:[2, 3, 1], [3, 1, 2]    输出:1

    代码:

     1 import java.util.*;
     2 
     3 
     4 public class Solution {
     5     /**
     6      * 
     7      * @param gas int整型一维数组 
     8      * @param cost int整型一维数组 
     9      * @return int整型
    10      */
    11     public int canCompleteCircuit (int[] gas, int[] cost) {
    12         // write code here
    13         int start = gas.length - 1;
    14         int end = 0;
    15         int sum = gas[start] - cost[start];
    16         while( start > end ){
    17             if( sum > 0 ){
    18                 sum += gas[end] - cost[end];
    19                 end ++;
    20             }else {
    21                 start --;
    22                 sum += gas[start] - cost[start];
    23             }
    24         }
    25         return sum >= 0 ? start : -1;
    26     }
    27 }

    笔记:  

      从 start 出发,如果油量足够,则一直向后走,即 end ++。如果油量不够,则需要向后退,即 start ++。最终,在 start == end 的时候,如果有解贼一定是当前 start 在的位置。

     

  • 相关阅读:
    Linux设备驱动之Ioctl控制
    虚拟内存与物理内存的区别
    怎么远程控制他人电脑
    二维数组和指针
    二维数组和指针(C语言)
    帧率、码流与分辨率相关知识
    深入理解FIFO
    安装lsb_release
    Linux初学之vmware Workstation 网络连接三种模式
    RTSP协议学习笔记
  • 原文地址:https://www.cnblogs.com/john1015/p/13696687.html
Copyright © 2011-2022 走看看