当前位置:   article > 正文

leetcode gas station

leetcode gas station

简单模拟题,改了半天

  1. public int canCompleteCircuit(int[] gas, int[] cost) {
  2. int n = gas.length;
  3. int tmp = 0,idx=0;
  4. if(n==1)
  5. return gas[0]>=cost[0]?0:-1;
  6. for(int i=0;i<n;i++){ //枚举起点
  7. idx = (i+1)%n;
  8. tmp = gas[i]-cost[i];//+gas[idx];
  9. if(tmp>=0)
  10. tmp += gas[idx];
  11. else
  12. continue;
  13. while(idx!=i && tmp>=0){
  14. if((idx+1)%n != i)
  15. tmp = tmp-cost[idx]+gas[(idx+1)%n];
  16. else
  17. tmp -= cost[idx];
  18. idx = (idx+1)%n;
  19. }
  20. if(idx==i && tmp>=0){
  21. return i;
  22. }
  23. }
  24. return -1;
  25. }
  1. 另外一个时间复杂度较低的解法,值得学习,即计算过的部分不浪费
  2. publicint canCompleteCircuit(vector<int> &gas, vector<int> &cost) {      
  3.         int start = gas.size() - 1;
  4.         int end = 0;
  5.         int sum = gas[start] - cost[start];
  6.         while(start > end){
  7.             if(sum >= 0){
  8.                 sum += gas[end] - cost[end];
  9.                 ++end;
  10.             }else{
  11.                 --start;
  12.                 sum += gas[start] - cost[start];
  13.             }
  14.         }
  15.         return sum >=0 ? start : -1;
  16.          
  17.          
  18.     }


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

闽ICP备14008679号