Skip to content

Commit 68f8c6e

Browse files
committed
solve problem Gas Station
1 parent 14cd0f5 commit 68f8c6e

File tree

5 files changed

+61
-0
lines changed

5 files changed

+61
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,7 @@ All solutions will be accepted!
297297
|623|[Add One Row To Tree](https://leetcode-cn.com/problems/add-one-row-to-tree/description/)|[java/py/js](./algorithms/AddOneRowToTree)|Medium|
298298
|513|[Find Bottom Left Tree Value](https://leetcode-cn.com/problems/find-bottom-left-tree-value/description/)|[java/py/js](./algorithms/FindBottomLeftTreeValue)|Medium|
299299
|103|[Binary Tree Zigzag Level Order Traversal](https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/description/)|[java/py/js](./algorithms/BinaryTreeZigzagLevelOrderTraversal)|Medium|
300+
|134|[Gas Station](https://leetcode-cn.com/problems/gas-station/description/)|[java/py/js](./algorithms/GasStation)|Medium|
300301

301302
# Database
302303
|#|Title|Solution|Difficulty|

Diff for: algorithms/GasStation/README.md

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Gas Station
2+
This problem is easy to solve

Diff for: algorithms/GasStation/Solution.java

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public int canCompleteCircuit(int[] gas, int[] cost) {
3+
int total = 0,
4+
diffSum = 0,
5+
start = 0;
6+
7+
for (int i = 0; i < gas.length; i++) {
8+
if (diffSum < 0) {
9+
diffSum = 0;
10+
start = i;
11+
}
12+
diffSum += gas[i] - cost[i];
13+
total += gas[i] - cost[i];
14+
}
15+
16+
return total >= 0 ? start : -1;
17+
}
18+
}

Diff for: algorithms/GasStation/solution.js

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* @param {number[]} gas
3+
* @param {number[]} cost
4+
* @return {number}
5+
*/
6+
var canCompleteCircuit = function(gas, cost) {
7+
let total = 0,
8+
diffSum = 0,
9+
start = 0
10+
11+
for (let i = 0; i < gas.length; i++) {
12+
if (diffSum < 0) {
13+
diffSum = 0
14+
start = i
15+
}
16+
diffSum += gas[i] - cost[i]
17+
total += gas[i] - cost[i]
18+
}
19+
20+
return total >= 0 ? start : -1
21+
};

Diff for: algorithms/GasStation/solution.py

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution(object):
2+
def canCompleteCircuit(self, gas, cost):
3+
"""
4+
:type gas: List[int]
5+
:type cost: List[int]
6+
:rtype: int
7+
"""
8+
total = 0
9+
diff_sum = 0
10+
start = 0
11+
12+
for i in xrange(len(gas)):
13+
if diff_sum < 0:
14+
diff_sum = 0
15+
start = i
16+
diff_sum += gas[i] - cost[i]
17+
total += gas[i] - cost[i]
18+
19+
return start if total >= 0 else -1

0 commit comments

Comments
 (0)