网站标题特效,昆明网站搜索优化,网站服务器和网站,国际物流公司leetcode 150道题 计划花两个月时候刷完#xff0c;今天#xff08;第五天#xff09;完成了1道(14)150#xff1a; 14. #xff08;134. 加油站#xff09;题目描述#xff1a;
在一条环路上有 n 个加油站#xff0c;其中第 i 个加油站有汽油 gas[i] 升。
你有一辆油…leetcode 150道题 计划花两个月时候刷完今天第五天完成了1道(14)150 14. 134. 加油站题目描述
在一条环路上有 n 个加油站其中第 i 个加油站有汽油 gas[i] 升。
你有一辆油箱容量无限的的汽车从第 i 个加油站开往第 i1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发开始时油箱为空。
给定两个整数数组 gas 和 cost 如果你可以按顺序绕环路行驶一周则返回出发时加油站的编号否则返回 -1 。如果存在解则 保证 它是 唯一 的。第一版暴力求解超时了好难啊想不到题解里面的想法。。垃圾暴力求解我就不放这了放一下吧暴力求解也写了好一会。。。
class Solution {public int canCompleteCircuit(int[] gas, int[] cost) {int gasAmount0;int costAmount0;int lengas.length;int[] amountnew int[len];for(int i0;ilen;i){gasAmountgas[i];costAmountcost[i];amount[i]gas[i]-cost[i];}if(gasAmountcostAmount){return -1;}for(int i0;ilen;i){if(amount[i]0){int rescanGo(amount,i);if(res!-1)return i;}}return -1; }public int canGo(int[] amount, int index){int lenamount.length;int tempindex;int sumamount[temp];temptemp%len;while(temp!index){if(sum0){return -1;}sumamount[temp];temptemp%len;}return index;}
}第二版看的题解说实话官方给的题解是真的看不懂 还得是评论区的通俗易懂总结就是找gas[i]-cost[i] 和的最小值然后最小值的下一个就是答案一脸懵逼的我
class Solution {public int canCompleteCircuit(int[] gas, int[] cost) {int gasAmount0;int costAmount0;int lengas.length;int[] amountnew int[len];for(int i0;ilen;i){gasAmountgas[i];costAmountcost[i];if(i0)amount[i]gas[i]-cost[i];else{amount[i]amount[i-1]gas[i]-cost[i];}}if(gasAmountcostAmount){return -1;}// 找最小的int minValueInteger.MAX_VALUE;int minIndex-1;for(int i0;ilen;i){if(amount[i]minValue){minValueamount[i];minIndexi;}}// 这个说是与一个案例有 bug 所以要加上这一句。。if(minValue0) return 0;return (minIndex1)%len;}
}早日跳槽明天好好刷今天周一加上周日失眠了各种debuff加满了。。。跳槽、跳槽