当前位置:   article > 正文

LeetCode | Gas Station_leetcode gas-station

leetcode gas-station

题目:

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.

Note:
The solution is guaranteed to be unique.

思路:

思路1:通过两层循环,依次从某个点出发并测试是否能够运行一圈。时间复杂度为O(n2),不满足要求。
思路2:首先确认gas总和大于cost,因此判断能够绕圈。接下来寻找起始位置,我们可以借鉴归并排序的思路,如果某一段路gas>cost,则这段路剩余的油量可以支撑其他路段。因此问题变化为找到某个节点,在它之前的路段剩余油量为负,而从它开始到整个队列结束剩余油量为正(正油量可以不足前面路段的不足油量)。时间可以在O(n)完成。


代码:

思路1:
  1. class Solution {
  2. public:
  3. int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
  4. for(int j=0;j<gas.size();j++)
  5. {
  6. int tank = 0;
  7. bool work = true;
  8. int i=j;
  9. do
  10. {
  11. tank+=gas[i];
  12. tank-=cost[i];
  13. if(tank < 0)
  14. {
  15. work = false;
  16. break;
  17. }
  18. i=(i+1)%gas.size();
  19. }while(i!=j);
  20. if(work)
  21. {
  22. return j;
  23. }
  24. }
  25. return -1;
  26. }
  27. };

思路2:
  1. class Solution {
  2. public:
  3. int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
  4. vector<int> remainder;
  5. int sum =0;
  6. for(int i = 0; i < gas.size(); i++)
  7. {
  8. remainder.push_back(gas[i]-cost[i]);
  9. sum += gas[i]-cost[i];
  10. }
  11. if(sum < 0)
  12. {
  13. return -1;
  14. }
  15. else
  16. {
  17. int start;
  18. int cur = 0;
  19. do
  20. {
  21. start = cur;
  22. int tmp = remainder[cur++];
  23. while(tmp >= 0 && cur<gas.size())
  24. {
  25. tmp += remainder[cur++];
  26. if(tmp < 0)
  27. {
  28. break;
  29. }
  30. }
  31. if(tmp >= 0 && cur == gas.size())
  32. {
  33. return start;
  34. }
  35. }while(cur<gas.size());
  36. return -1;
  37. }
  38. }
  39. };





声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/493515
推荐阅读
相关标签
  

闽ICP备14008679号