134. 加油站
方法一
class Solution {
public :
int canCompleteCircuit ( vector< int > & gas, vector< int > & cost) {
int minSpare = std:: numeric_limits < int > :: max ( ) ;
int spare = 0 ;
int len = gas. size ( ) ;
int index = 0 ;
for ( int i = 0 ; i < len; i++ ) {
spare += gas[ i] - cost[ i] ;
if ( spare < minSpare) {
minSpare = spare;
index = i;
}
}
if ( spare < 0 ) return - 1 ;
if ( minSpare >= 0 ) return 0 ;
return ( index + 1 ) % len;
}
} ;
方法二
class Solution {
public :
int canCompleteCircuit ( vector< int > & gas, vector< int > & cost) {
int length = gas. size ( ) ;
vector< int > dValue ( length) ;
for ( int i = 0 ; i < length; i++ ) {
dValue[ i] = gas[ i] - cost[ i] ;
}
int start = 0 ;
while ( start < length) {
int curSum = 0 , count = 0 ;
while ( count < length) {
curSum += dValue[ ( start+ count) % length] ;
if ( curSum < 0 ) {
break ;
}
count++ ;
}
if ( count == length) {
return start;
}
else {
start = start + count + 1 ;
}
}
return - 1 ;
}
} ;
class Solution {
public :
int canCompleteCircuit ( vector< int > & gas, vector< int > & cost) {
int length = gas. size ( ) , start = 0 ;
while ( start < length) {
int curSum = 0 , count = 0 ;
while ( count < length) {
curSum = curSum + gas[ ( start+ count) % length] - cost[ ( start+ count) % length] ;
if ( curSum < 0 ) {
break ;
}
count++ ;
}
if ( count == length) {
return start;
}
else {
start = start + count + 1 ;
}
}
return - 1 ;
}
} ;