Skip to content

Commit f1d2144

Browse files
committed
134. Gas Station
1 parent f58fd6f commit f1d2144

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@
22

33
Not only Leetcode solutions in Swift.
44

5-
* [1.Two Sum](https://leetcode.com/problems/two-sum/)
5+
* [1. Two Sum](https://leetcode.com/problems/two-sum/)
66
* [15. 3Sum](https://leetcode.com/problems/3sum/)
77
* [16. 3Sum Closest](https://leetcode.com/problems/3sum-closest/)
88
* [18. 4Sum](https://leetcode.com/problems/4sum/)
99
* [46. Group Anagrams](https://leetcode.com/problems/anagrams/)
10+
* [134. Gas Station](https://leetcode.com/problems/gas-station/)
1011
* [167. Two Sum II - Input array is sorted](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/)
1112
* [170. Two Sum III - Data structure design](https://leetcode.com/problems/two-sum-iii-data-structure-design)
1213
* [Two Sum - Less than or equal to target](http://www.lintcode.com/en/problem/two-sum-less-than-or-equal-to-target/)

SwiftyLeetCode.playground/Contents.swift

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,36 @@ extension Solution {
227227
let groupAnagramsStrs = ["eat", "tea", "tan", "ate", "nat", "bat"]
228228
Solution.groupAnagrams(strs: groupAnagramsStrs)
229229

230+
/**
231+
* 134. Gas Station
232+
* https://leetcode.com/problems/gas-station/
233+
*/
234+
235+
extension Solution {
236+
class func canCompleteCircuit(gas: [Int]?, cost: [Int]?) -> Int {
237+
238+
guard let gas = gas, let cost = cost, gas.count > 0, cost.count > 0 else {
239+
return -1
240+
}
241+
242+
var sum = 0
243+
var total = 0
244+
var index = -1
245+
246+
for i in 0..<gas.count {
247+
sum += gas[i] - cost[i]
248+
total += gas[i] - cost[i]
249+
250+
if (sum < 0) {
251+
index = i
252+
sum = 0
253+
}
254+
}
255+
256+
return total < 0 ? -1 : index + 1
257+
}
258+
}
259+
230260
/**
231261
* 167. Two Sum II - Input array is sorted
232262
* https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/

0 commit comments

Comments
 (0)