直接用brute force,注意数组的循环遍历怎么访问,这里用do {} while();
每个元素访问两遍,时间复杂度O(N^2),当然可以优化到O(N)。
class Solution {
public:
int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
for (int i = 0; i < gas.size(); i++) {
if (helper(i, gas, cost))
return i;
}
return -1;
}
private:
bool helper(int pos, vector<int>& gas, vector<int>& cost) {
int index = pos;
int rest = 0;
/*此处do...while...环形遍历数组*/
do{
rest += gas[index] - cost[index];
if (rest < 0)
return false;
if (index == gas.size()-1)
index = 0;
else
index++;
}while(index!=pos);
return true;
}
};