zoukankan      html  css  js  c++  java
  • leetcode——134.加油站

    自己完成了,但是效果好像并不怎么样

    public int canCompleteCircuit(int[] gas, int[] cost) {
            int len = gas.length;
            if(len == 1){
                return gas[0] >= cost[0]?0:-1;
            }
            int sum1 = 0,sum2 = 0;
            for(int i = 0;i<len;i++){
                sum1 += gas[i];
                sum2 += cost[i];
            }
            if(sum2 > sum1){
                return -1;
            }
            int start = 0;
            while (start < len) {
                while(gas[start] < cost[start]) {
                    start++;
                }
                int begin = start;
                int res = gas[start];
                for(;begin <= len;begin++) {
                    if(begin == len){
                        begin = 0;
                    }
                    res = res - cost[begin] + gas[(begin + 1)%len];  //res小于0的时候,要移动start的位置,要怎么做到
                    if(res < 0 || res - gas[(begin + 1)%len] < 0){
                        start++;
                        break;
                    }
                    if(start - 2 >=  0 && begin == start -2 || start - 2 < 0 && begin == len + start - 2){
                        if(res >= cost[(start - 1 + len)%len]){
                            return start;
                        }else{
                            return -1;
                        }
                    }
                }
            }
            return -1;
        }

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

     多简洁。

    ——2020.7.13

    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    New-SAN-FENG-YUN-三
    San丰-Cloud
    SpringBoot+MySQL+MyBatis+Shiro+AdminLTE
    SanFeng-Clound
    SanFengClound
    传奇音乐设置
    热血传奇GOM引擎问题集锦
    app测试
    接口测试
    题目
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/13292018.html
Copyright © 2011-2022 走看看