leetcode134 Gas Station

 1 """
 2 There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
 3 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.
 4 Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1.
 5 Note:
 6     If there exists a solution, it is guaranteed to be unique.
 7     Both input arrays are non-empty and have the same length.
 8     Each element in the input arrays is a non-negative integer.
 9 Example 1:
10 Input:
11 gas  = [1,2,3,4,5]
12 cost = [3,4,5,1,2]
13 Output: 3
14 Explanation:
15 Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
16 Travel to station 4. Your tank = 4 - 1 + 5 = 8
17 Travel to station 0. Your tank = 8 - 2 + 1 = 7
18 Travel to station 1. Your tank = 7 - 3 + 2 = 6
19 Travel to station 2. Your tank = 6 - 4 + 3 = 5
20 Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
21 Therefore, return 3 as the starting index.
22 Example 2:
23 Input:
24 gas  = [2,3,4]
25 cost = [3,4,3]
26 Output: -1
27 Explanation:
28 You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
29 Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
30 Travel to station 0. Your tank = 4 - 3 + 2 = 3
31 Travel to station 1. Your tank = 3 - 3 + 3 = 3
32 You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
33 Therefore, you can't travel around the circuit once no matter where you start.
34 """
35 """
36 解法一:自己AC
37 按照题目要求正常实现
38 """
39 class Solution1:
40     def canCompleteCircuit(self, gas, cost):
41         cur = 0
42         for i in range(len(gas)):
43             cur = gas[i]
44             for j in range(i, i+len(gas)):
45                 cur -= cost[j % len(gas)]
46                 if cur < 0:
47                     break
48                 cur += gas[(j+1) % len(gas)]
49             if cur >= 0:
50                 return i
51         return -1
52 """
53 解法二:算法思想,主要遵从两个原则:
54 1.出发点必须满足gas>cost,否则不可能出发
55 2.总的gas>cost,否则一定走不完
56 """
57 class Solution:
58     def canCompleteCircuit(self, gas, cost):
59         total = 0
60         res = 0
61         cur = 0
62         for i in range(len(gas)):
63             cur += gas[i] - cost[i]
64             if cur < 0:
65                 res = i + 1
66                 total += cur
67                 cur = 0
68         return res if (total + cur) >= 0 else -1
69 if __name__ == '__main__':
70     gas = [1, 2, 3, 4, 5]
71     cost = [3, 4, 5, 1, 2]
72     ans = Solution1()
73     print(ans.canCompleteCircuit(gas, cost))

 

posted @ 2020-03-12 00:16  yawenw  阅读(166)  评论(0编辑  收藏  举报