简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
There are N gas stations along a circular route, where the amount of gas at station i is
gas[i]
.
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.
Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.
Note:
The solution is guaranteed to be unique.
The solution is guaranteed to be unique.
题没什么难的,就是要注意这是一个circular route, i后面连接的是0,所以index需要处理,而走了多远要用一个额外的变量记录。
刚开始一直time limit exceed,因为我是一个一个station作为start去尝试,后来想其实没必要,因为假如一旦有一个route走不通,我们重新开始的station应该是我们中断的下一个,因为前面的任何一个开始都不会可以,可以证明出来,不细说了,自己想想就可以知道。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) { | |
// Note: The Solution object is instantiated only once and is reused by each test case. | |
int gasVal=0; | |
int len=gas.size(); | |
for(int i=0; i<gas.size(); i++) | |
{ | |
int j=i; | |
int count = 1; | |
gasVal=0; | |
while(count<=gas.size()) | |
{ | |
if(gasVal+gas[j%len]>=cost[j%len]) | |
{ | |
if(count==gas.size()) return i; | |
gasVal = gasVal+gas[j%len]-cost[j%len]; | |
j++; | |
count++; | |
} | |
else | |
{ | |
i=j; | |
break; | |
} | |
} | |
} | |
return -1; | |
} | |
}; |
有个问题想请教下
ReplyDeleteelse
{
i=j;
break;
}
这里为什么是i=j; 而不是i=j%gas.size();呢? 谢谢~~