大型服裝商城網(wǎng)站建設(shè)世界羽聯(lián)巡回賽總決賽
在一條環(huán)路上有 n 個加油站,其中第 i 個加油站有汽油 gas[i] 升。
你有一輛油箱容量無限的的汽車,從第 i 個加油站開往第 i+1 個加油站需要消耗汽油 cost[i] 升。你從其中的一個加油站出發(fā),開始時油箱為空。
給定兩個整數(shù)數(shù)組 gas 和 cost ,如果你可以繞環(huán)路行駛一周,則返回出發(fā)時加油站的編號,否則返回 -1 。如果存在解,則 保證 它是 唯一 的。
https://leetcode.cn/problems/gas-station/
/** Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.*/package com.huawei.prac;import java.util.Arrays;public class Solution7th {public static void main(String[] args) {int[] gas = {1, 2, 3, 4, 5};int[] cost = {3, 4, 5, 1, 2};System.out.println(canCompleteCircuit(gas, cost));}/*** 134. 加油站[簡單模擬 + 邏輯轉(zhuǎn)化]** @param gas 已有汽油* @param cost 所需汽油* @return 可繞環(huán)路行駛一周的起點*/public static int canCompleteCircuit(int[] gas, int[] cost) {int sumGas = Arrays.stream(gas).sum();int sumCost = Arrays.stream(cost).sum();if (sumCost > sumGas) {return -1;}int[] cha = new int[gas.length];for (int i = 0; i < cha.length; i++) {cha[i] = gas[i] - cost[i];}int sum;int index;for (int i = 0; i < cha.length; i++) {if (cha[i] > 0) {index = i;sum = cha[i];boolean find = true;for (int j = i + 1; j < cha.length; j++) {sum += cha[j];if (sum < 0) {find = false;break;}}if (find) {return index;}}}// 特殊情況:差值為零return 0;}
}