今日记录
134.加油站
Leetcode链接
class Solution {
public :
int canCompleteCircuit ( vector< int > & gas, vector< int > & cost) {
int curSum = 0 ;
int totalSum = 0 ;
int start = 0 ;
for ( int i = 0 ; i < gas. size ( ) ; i++ ) {
curSum += gas[ i] - cost[ i] ;
totalSum += gas[ i] - cost[ i] ;
if ( curSum < 0 ) {
start = i + 1 ;
curSum = 0 ;
}
}
if ( totalSum < 0 )
return - 1 ;
return start;
}
} ;
135.分发糖果
Leetcode链接
class Solution {
public :
int candy ( vector< int > & ratings) {
vector< int > candyVec ( ratings. size ( ) , 1 ) ;
for ( int i = 1 ; i < ratings. size ( ) ; i++ ) {
if ( ratings[ i] > ratings[ i - 1 ] )
candyVec[ i] = candyVec[ i - 1 ] + 1 ;
}
for ( int i = ratings. size ( ) - 2 ; i >= 0 ; i-- ) {
if ( ratings[ i] > ratings[ i + 1 ] ) {
candyVec[ i] = max ( candyVec[ i] , candyVec[ i + 1 ] + 1 ) ;
}
}
int result = 0 ;
for ( int i = 0 ; i < candyVec. size ( ) ; i++ ) {
result += candyVec[ i] ;
}
return result;
}
} ;
860.柠檬水找零
Leetcode链接
class Solution {
public :
bool lemonadeChange ( vector< int > & bills) {
vector< int > count ( 2 , 0 ) ;
if ( bills[ 0 ] != 5 )
return false ;
else
count[ 0 ] ++ ;
for ( int i = 1 ; i < bills. size ( ) ; i++ ) {
if ( bills[ i] == 5 )
count[ 0 ] ++ ;
if ( bills[ i] == 10 ) {
count[ 0 ] -- ;
count[ 1 ] ++ ;
}
if ( bills[ i] == 20 ) {
if ( count[ 1 ] > 0 ) {
count[ 0 ] -- ;
count[ 1 ] -- ;
} else {
count[ 0 ] -= 3 ;
}
}
if ( count[ 0 ] < 0 || count[ 1 ] < 0 )
return false ;
}
return true ;
}
} ;
406.根据身高重建队列
Leetcode链接
class Solution {
public :
static bool cmp ( const vector< int > & a, const vector< int > & b) {
if ( a[ 0 ] == b[ 0 ] )
return a[ 1 ] < b[ 1 ] ;
return a[ 0 ] > b[ 0 ] ;
}
vector< vector< int >> reconstructQueue ( vector< vector< int >> & people) {
sort ( people. begin ( ) , people. end ( ) , cmp) ;
vector< vector< int >> que;
for ( int i = 0 ; i < people. size ( ) ; i++ ) {
int position = people[ i] [ 1 ] ;
que. insert (
que. begin ( ) + position,
people[ i] ) ;
}
return que;
}
} ;
总结