670. 最大交换
代码实现
class Solution {
public :
int maximumSwap ( int num) {
if ( num < 10 ) return num;
int tmp = num;
vector< int > arr;
while ( tmp) {
arr. insert ( arr. begin ( ) , tmp % 10 ) ;
tmp /= 10 ;
}
vector< int > tmp1 = arr;
sort ( tmp1. begin ( ) , tmp1. end ( ) , greater < int > ( ) ) ;
int i = 0 ;
for ( ; i < arr. size ( ) ; i++ ) {
if ( tmp1[ i] != arr[ i] ) break ;
}
if ( i == arr. size ( ) ) return num;
int j = i;
int sub = j, maxNum = 0 ;
for ( ; i < arr. size ( ) ; i++ ) {
if ( arr[ i] >= maxNum) {
maxNum = arr[ i] ;
sub = i;
}
}
swap ( arr[ j] , arr[ sub] ) ;
int ans = 0 ;
for ( int i = 0 ; i < arr. size ( ) ; i++ ) {
ans = ans * 10 + arr[ i] ;
}
return ans;
}
} ;
1306. 跳跃游戏 III
代码实现
class Solution {
public :
bool canReach ( vector< int > & arr, int start) {
int n = arr. size ( ) ;
vector< bool > visited ( n, false ) ;
queue< int > myQueue;
myQueue. push ( start) ;
int tmp;
while ( ! myQueue. empty ( ) ) {
tmp = myQueue. front ( ) ;
myQueue. pop ( ) ;
if ( visited[ tmp] ) continue ;
visited[ tmp] = true ;
if ( ! arr[ tmp] ) return true ;
if ( tmp + arr[ tmp] < n) myQueue. push ( tmp + arr[ tmp] ) ;
if ( tmp - arr[ tmp] >= 0 ) myQueue. push ( tmp - arr[ tmp] ) ;
}
return false ;
}
} ;
1654. 到家的最少跳跃次数
代码实现
class Solution {
public :
int minimumJumps ( vector< int > & forbidden, int a, int b, int x) {
queue< pair< int , int >> myQueue;
set< int > f;
for ( auto & b : forbidden) {
f. emplace ( b) ;
}
set< pair< int , int >> visited;
myQueue. push ( { x, 0 } ) ;
int t = 0 ;
while ( ! myQueue. empty ( ) ) {
int sz = myQueue. size ( ) ;
while ( sz-- ) {
auto [ loc, time] = myQueue. front ( ) ;
myQueue. pop ( ) ;
if ( loc == 0 ) return t;
if ( f. count ( loc) || visited. count ( make_pair ( loc, time) ) ) continue ;
visited. emplace ( make_pair ( loc, time) ) ;
if ( loc < 0 ) continue ;
if ( loc > 6000 ) continue ;
myQueue. push ( { loc - a, 0 } ) ;
if ( ! time) myQueue. push ( { loc + b, 1 } ) ;
}
t++ ;
}
return - 1 ;
}
} ;
365. 水壶问题
代码实现
class Solution {
public :
bool canMeasureWater ( int x, int y, int z) {
if ( x + y < z) return false ;
if ( x == 0 || y == 0 ) return z == 0 || ( x + y) == z;
return z % gcd ( x, y) == 0 ;
}
} ;