-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path134.cpp
More file actions
35 lines (32 loc) · 873 Bytes
/
134.cpp
File metadata and controls
35 lines (32 loc) · 873 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//
// 134.cpp
// LeetCode
//
// Created by 张佐玮 on 15/6/28.
// Copyright (c) 2015年 JarvisZhang. All rights reserved.
//
// Title: Gas Station
//
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
if (gas.empty() || cost.empty()) {
return -1;
}
int start = 0, end = 0, current = gas[start] - cost[start], length = (int) gas.size();
while (start % length != (end + 1) % length) {
if (current > 0) {
end = (end + 1) % length;
current += gas[end] - cost[end];
}
else {
start = (start + length - 1) % length;
current += gas[start] - cost[start];
}
}
return current >= 0 ? start : -1;
}
};