LeetCode Notebook 2020-2021
  • 序
  • 目录
  • 线性表
    • 数组
      • Remove Duplicates from Sorted Array
      • Remove Duplicates from Sorted Array II
      • Exercises I
      • Search in Rotated Sorted Array
      • Search in Rotated Sorted Array II
      • Median of Two Sorted Arrays
      • Longest Consecutive Sequence
      • Exercises II
      • Two Sum
      • 3Sum
      • 3Sum Closest
      • 4Sum
      • Exercises III
      • Next Permutation
      • Permutation Sequence
      • Exercises IV
      • Valid Sudoku
      • Trapping Rain Water
      • Rotate Image
      • Plus One
      • Exercises V
      • Climbing Stairs
      • Set Matrix Zeroes
      • Gray Code
      • Gas Station
      • Exercises VI
      • Candy
      • Single Number
      • Single Number II
      • Exercises VII
    • 链表
      • Add Two Numbers
      • Reverse Linked List II
      • Partition List
      • Swap-nodes-in-pairs
  • 字符串
    • 字符串
      • Valid Palindrome
      • Implement strStr()
      • String to Integer(atoi)
      • Add Binary
      • Longest Palindromic Substring
      • Longest Common Subsequence
      • Regular Expression Matching
      • Rearrange Spaces Between Words
      • Longest Common Prefix
      • Wildcard Matching
      • subdomain visit count
  • 栈和队列
    • 栈
      • Min Stack
      • Valid Parentheses
    • 队列
  • 树
    • 二叉树的遍历
      • Binary Tree Preorder Traversal
      • Binary Tree Inorder Traversal
      • Binary Tree Postorder Traversal
      • Search in a Binary Search Tree
    • 二叉树的构造
      • Untitled
    • 二叉查找树
      • Validate Binary Search Tree
    • 二叉树的递归
      • Untitled
  • 图
    • 图
  • 排序
    • 排序
      • Merge Sorted Array
      • Merge Two Sorted Lists
      • Merge k Sorted Lists
      • Exercises I
      • Insertion Sort List
      • Sort List
      • Sort Color
      • First Missing Positive
      • Exercises II
  • 查找
    • 查找
      • Random Pick with Weight
      • Prefix and Suffix Search
      • Search Insert Position
      • Search a 2D Matrix
  • BFS
    • BFS
  • DFS
    • DFS
      • Split a String Into the Max Number of Unique Substrings
      • Palindrome Partitioning
      • Unique Path
      • Unique Path II
  • 动态规划
    • DP
      • Coin Change
      • Maximal Rectangle
      • Super Egg Drop
      • Exercises
      • Best Team With No Conflicts
  • 分治法
    • Divide And Conquer
  • 贪心法
    • Greedy
      • Jump Game
      • Jump Game II
      • Best time to buy and sell stock
      • Best time to buy and sell stock II
      • Container with most water
      • Exercises
  • 暴力枚举
    • Brute Force
      • Subsets
      • Subsets II
      • Permutation
      • Permutation II
      • Combinations
      • Letter Combinations of a Phone Number
  • others
    • 小岛题
    • 滑动窗口
      • Longest substring without repeating characters
      • Sliding Window Maximum
      • Max Consecutive One III
      • Count Number of Nice Subarrays
    • Roman number code
    • Untitled
由 GitBook 提供支持
在本页
  • Gas Station
  • 描述
  • 例子
  • 解法 Brute Force
  • 解法 Math

这有帮助吗?

  1. 线性表
  2. 数组

Gas Station

medium 原题链接:https://leetcode.com/problems/gas-station/

上一页Gray Code下一页Exercises VI

最后更新于4年前

这有帮助吗?

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 in the clockwise direction, otherwise return -1.

Note:

  • If there exists a solution, it is guaranteed to be unique.

  • Both input arrays are non-empty and have the same length.

  • Each element in the input arrays is a non-negative integer.

例子

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

Output: 3

Explanation: Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 4. Your tank = 4 - 1 + 5 = 8 Travel to station 0. Your tank = 8 - 2 + 1 = 7 Travel to station 1. Your tank = 7 - 3 + 2 = 6 Travel to station 2. Your tank = 6 - 4 + 3 = 5 Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. Therefore, return 3 as the starting index.

解法 Brute Force

乍一看是O(n^2)的问题,即对每个点进行模拟。。

事实上,可以设置两个变量,sum来判断当前的i的有效性;totoal则判断整个组是否有解。从gas的0起点开始,依次遍历,遇到gas-cost<0时候,break;直到到可以走通的一个完整的clockwise,不然就返回-1。

时间复杂度:O(n)

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int sumGas=0;
        int sumCost=0;
        int start=0;
        int tank=0;
        for(int i=0; i<gas.size(); i++){
            sumGas+=gas[i];
            sumCost+=cost[i];
            tank+=gas[i]-cost[i];
            if(tank<0){
                start=i+1;
                tank=0;
            }
        }
        return sumGas-sumCost<0? -1:start;
    }
};

解法 Math

时间复杂度:O(1)

Explanation:

The main idea is that every time we go to the next station as far as possible (remained gas is bigger or equal to 0) until we can not (remained gas is less than 0). Then we must extend our start station to the "last station" ( the station before start station) to find a possible solution. Repeat these two steps until we have checked all stations(start == end).

We can travel around the circuit only if the remained gas is bigger or equal to 0!

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
       int start = gas.size()-1;
       int end = 0;
       int sum = gas[start] - cost[start];
       while (start > end) {
          if (sum >= 0) {
             sum += gas[end] - cost[end];
             ++end;
          }
          else {
             --start;
             sum += gas[start] - cost[start];
          }
       }
       return sum >= 0 ? start : -1;
    }
};

原题链接