LeetCode134——加油站

版权声明:我的GitHub:https://github.com/617076674。真诚求星! https://blog.csdn.net/qq_41231926/article/details/85521304

我的LeetCode代码仓:https://github.com/617076674/LeetCode

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

题目描述:

知识点:数组

思路一:逐个判断每个位置是否符合条件

对每个索引位置都依次判断是否能从该位置开始绕环路行驶一周。

时间复杂度和输入的数据有关,在最坏的情况下是O(n ^ 2),其中n为加油站的数量。空间复杂度是O(1)。

JAVA代码:

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int start = -1;
        for(int i = 0; i < gas.length; i++){
            if(gas[i] >= cost[i]){
                int sum = 0;
                int j = 0;
                for(; j < gas.length; j++){
                    sum += gas[(i + j) % gas.length] - cost[(i + j) % gas.length];
                    if(sum < 0){
                        break;
                    }
                }
                if(j >= gas.length){
                    start = i;
                    break;
                }
            }
        }
        return start;
    }
}

LeetCode解题报告:

思路二:如果以第i个位置为起点,在第j个点发现不满足题意,则下一个待判定的起点可以定为j + 1

对于每一个待确定的起点i,如果从i开始到j之和sum小于0,那么下一个待确定的起点就可以是j + 1,同时重置sum和为gas[j + 1] - cost[j + 1],这就跳过了对[i + 1, j]区间内起点的判断。如果sum之和大于等于0,那么只需更新sum值,在原来基础上加上gas[j + 1] - cost[j + 1]即可。

如果gas数组中所有元素之和小于cost数组中所有元素之和,则需返回-1,即不存在解决方案。

时间复杂度是O(n)。空间复杂度是O(1)。

JAVA代码:

class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int start = 0;
        int total = 0;  //gas所有元素和-cost所有元素和
        int sum = 0;    //从start位置开始,gas中元素和-cost中元素和
        for(int i = 0; i < gas.length; i++){
            total += gas[i] - cost[i];
            if(sum < 0){
                sum = gas[i] - cost[i];
                start = i;
            }else{
                sum += gas[i] - cost[i];
            }
        }
        if(total < 0){
            return -1;
        }
        return start;
    }
}

LeetCode解题报告:

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/85521304