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

    这题理解题意之后很简单,即要保证gas - cost 的和一直是正的就可以了。 但是要注意这是一个circular。

     1 public class Solution {
     2     public int canCompleteCircuit(int[] gas, int[] cost) {
     3         // Note: The Solution object is instantiated only once and is reused by each test case.
     4         if(gas.length == 0) return -1;
     5         for(int i = 0; i < gas.length; i ++){
     6             gas[i] = gas[i] - cost[i];
     7         }
     8         for(int i = 0; i < gas.length; i ++){
     9             int sum = 0;
    10             boolean sig = true;
    11             for(int j = i; j < gas.length; j ++){
    12                 sum += gas[j];
    13                 if(sum < 0){
    14                     sig = false;
    15                     break;
    16                 }
    17             }
    18             for(int j = 0; j < i; j ++){
    19                 sum += gas[j];
    20                 if(sum < 0){
    21                     sig = false;
    22                     break;
    23                 }
    24             }
    25             if(sig == true)return i;
    26         }
    27         return -1;
    28     }
    29 }
  • 相关阅读:
    [SDOI2015] 序列统计
    [BZOJ3514] Codechef MARCH14 GERALD07加强版
    [CF1082E] Increasing Frequency
    [CF1093G] Multidimensional Queries
    [HNOI2013] 切糕
    [HEOI2017] 寿司餐厅 + 最大权闭合子图的总结
    [BZOJ3771] Triple
    [HEOI2016] 字符串
    [总结] 后缀数组学习笔记
    [Luogu 3613] 睡觉困难综合征
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3375353.html
Copyright © 2011-2022 走看看