leetcode134~Gas Station
来源:互联网 发布:思维脑图软件 编辑:程序博客网 时间:2024/05/01 06:06
There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. Return the starting gas station’s index if you can travel around the circuit once, otherwise return -1.
思路:
方法一:每个站点都作为起始点,开始遍历,判断油差是否小于0,如果小于,则以下一个站点为起始点继续执行上述过程,如果不小于,则带着之前的剩油量继续向前走,直至小于0或者遍历结束。这样解法时间复杂度是O(n^2),在leetcode中会超时。
方法二:只需要一次遍历,时间复杂度O(n).
从第0个站点开始,假设到p站点时,油差<0 sum1 = diff[0] +diff[1] + … + diff[p]<0。下面只需要选择p+1站点作为起始点即可,不需要从第1个站点尝试,因为这样可能还没到p,sum就小于0了,少加了站点0的油。在遍历到最后的时候,还有必要绕圈回来,再次验证么?这是不需要的。只需要记录一个变量用来存储所有的油差,如果小于0,
则不存在这样站点,如果不小于0,则肯定满足。
//时间复杂度O(n) public int canCompleteCircuit(int[] gas, int[] cost) { if(gas==null || cost==null || gas.length==0 || cost.length==0) return -1; //记录总共的差值 int total = 0; //从i个站点出发 差值 int sum = 0; //记录上一个站点的位置 int index = -1; for(int i=0;i<gas.length;i++) { sum += gas[i] - cost[i]; total += gas[i] - cost[i]; if(sum<0) { index = i; sum = 0; } } if(total<0) { return -1; } else { return index+1; } } public int canCompleteCircuit3(int[] gas, int[] cost) { //依次从每一个加油站出发 for (int i = 0; i < gas.length; i++) { int j = i; int curgas = gas[j]; while (curgas >= cost[j]) { //如果当前的汽油量能够到达下一站 curgas -= cost[j]; //减去本次的消耗 j = (j + 1) % gas.length; //到达下一站 if (j == i) return i; //如果回到了起始站,那么旅行成功 curgas += gas[j]; //到下一站后重新加油,继续前进 } } return -1; }
- LeetCode134. Gas Station
- LeetCode134—Gas Station
- LeetCode134.. Gas Station
- leetcode134~Gas Station
- leetcode134. Gas Station
- leetcode134. Gas Station
- LeetCode134 Gas Station
- LeetCode134——Gas Station
- leetcode134 Gas Station java 算法
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- Gas Station
- fatal error C1083: Cannot open precompiled header file: 'Debug/***.pch': No such file or directory
- 树的层次遍历
- Java线程安全和非线程安全
- 显示器的分辨率,字体像素
- .NET vs2010中使用IrisSkin2.dll轻松实现winForm窗体换肤功能
- leetcode134~Gas Station
- #pragma预处理命令
- 表达式与操作符
- Spring Beans实例化
- 使用MapReduce统计微博关注数据
- 前端面试答案整理之js
- 如何在win10本地安装wordpress测试环境
- Java提高篇(二七)-----TreeMap
- 归并排序详解