zoukankan      html  css  js  c++  java
  • gas-station

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

    /**
     *环形路上有n个加油站,第i个加油站的汽油量是gas[i].
     * 你有一辆车,车的油箱可以无限装汽油。从加油站i走到下一个加油站(i+1)花费的油量是cost[i],你从一个加油站出发,刚开始的时候油箱里面没有汽油。
     * 求从哪个加油站出发可以在环形路上走一圈。返回加油站的下标,如果没有答案的话返回-1。
     * 注意:
     * 答案保证唯一。
     *
     */
    
    public class Main56 {
        public static void main(String[] args) {
            int[] gas = {41,42,3,4,45};
            int[] cost = {1,2,63,64,5};
            System.out.println(Main56.canCompleteCircuit(gas, cost));
        }
    
        public static int canCompleteCircuit(int[] gas, int[] cost) {
    
            int[] rest = new int[gas.length];
            for (int i=0;i<gas.length;i++) {
                rest[i] = gas[i] - cost[i];
            }
            int index = 0;
            int total = 0;
            for (int i=0;i<rest.length;i++) {
                total = total + rest[i];
                if (rest[i] < 0) {
                    index = i+1;
                }
            }
            return total >= 0 ? index : -1;
        }
    }
    

      

  • 相关阅读:
    线性回归和逻辑回归
    行列式,叉积 (2)
    K最邻近算法(K-Nearest Neighbor,KNN)(初探)
    线性感知机和SVM(初探)
    向量点积(Dot Product)
    聚类(初探)
    sqlserver全文检索
    诗词背诵
    初级英语04
    初级英语03
  • 原文地址:https://www.cnblogs.com/strive-19970713/p/11376072.html
Copyright © 2011-2022 走看看