C++ algorithm learning (Likou: 134. Gas station)

There are N gas stations on a ring road, and the i-th gas station has gasoline gas[i] liters.

You have a car with an unlimited fuel tank. Driving from the i-th gas station to the i+1-th gas station requires cost[i] liters of gasoline. You start from one of the gas stations and the gas tank is empty at the beginning.

If you can go around the loop, return the number of the gas station when you started, otherwise return -1.

Description:

If the question has a solution, that answer is the only answer.
The input arrays are all non-empty arrays and have the same length.
The elements in the input array are all non-negative numbers.
Example 1:

输入: 
gas  = [1,2,3,4,5]
cost = [3,4,5,1,2]

输出: 3

解释:3 号加油站(索引为 3)出发,可获得 4 升汽油。此时油箱有 = 0 + 4 = 4 升汽油
开往 4 号加油站,此时油箱有 4 - 1 + 5 = 8 升汽油
开往 0 号加油站,此时油箱有 8 - 2 + 1 = 7 升汽油
开往 1 号加油站,此时油箱有 7 - 3 + 2 = 6 升汽油
开往 2 号加油站,此时油箱有 6 - 4 + 3 = 5 升汽油
开往 3 号加油站,你需要消耗 5 升汽油,正好足够你返回到 3 号加油站。
因此,3 可为起始索引。

Example 2:

输入: 
gas  = [2,3,4]
cost = [3,4,3]

输出: -1

解释:
你不能从 0 号或 1 号加油站出发,因为没有足够的汽油可以让你行驶到下一个加油站。
我们从 2 号加油站出发,可以获得 4 升汽油。 此时油箱有 = 0 + 4 = 4 升汽油
开往 0 号加油站,此时油箱有 4 - 3 + 2 = 3 升汽油
开往 1 号加油站,此时油箱有 3 - 3 + 3 = 3 升汽油
你无法返回 2 号加油站,因为返程需要消耗 4 升汽油,但是你的油箱只有 3 升汽油。
因此,无论怎样,你都不可能绕环路行驶一周。

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/gas-station The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Personal problem solution: The purpose of this problem is to find whether the oil is enough to the end, then we need to judge two points: 1. The total oil can run all the way, this is a solution. 2. If there is a solution, start looking for the first solution.

class Solution {
    
    
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
    
    
      int gas_min_cost = 0;//总油数量
      int start = 0; //起始位置
      int num = 0;  //每次的数
      for(int i = 0;i < gas.size();i++){
    
    
      num += (gas[i] - cost[i]);
      gas_min_cost +=(gas[i] - cost[i]);
      if(num < 0){
    
    
       start = i+1;
       num = 0;   
      }
      }
     if(gas_min_cost <0 ) return -1;
      return start;
    }
};

Guess you like

Origin blog.csdn.net/weixin_45743162/article/details/109779868