两数之和
vector< int > twoSum ( vector< int > & nums, int target) {
vector< int > v ( nums. size ( ) ) ;
for ( int i = 0 ; i < v. size ( ) ; ++ i) {
v[ i] = nums[ i] ;
}
ranges:: sort ( v) ;
int left = 0 , right = v. size ( ) - 1 ;
while ( left < right) {
while ( left < right && v[ right] > target - v[ left] ) {
-- right;
}
while ( left < right && v[ left] < target - v[ right] ) {
++ left;
}
if ( left < right && v[ left] + v[ right] == target) {
break ;
}
}
vector< int > ret ( 2 ) ;
for ( int i = 0 ; i < nums. size ( ) ; ++ i) {
if ( nums[ i] == v[ left] ) {
ret[ 0 ] = i;
break ;
}
}
for ( int i = nums. size ( ) - 1 ; i >= 0 ; -- i) {
if ( nums[ i] == v[ right] ) {
ret[ 1 ] = i;
break ;
}
}
return ret;
}
unordered_map< int , int > hash;
vector< int > twoSum ( vector< int > & nums, int target) {
for ( int i = 0 ; i < nums. size ( ) ; ++ i) {
if ( hash. count ( target - nums[ i] ) > 0 ) {
return { hash[ target - nums[ i] ] , i} ;
} else {
hash[ nums[ i] ] = i;
}
}
return { - 1 , - 1 } ;
}
判定是否互为字符重排
bool CheckPermutation ( string s1, string s2) {
if ( s1. size ( ) != s2. size ( ) ) return false ;
vector< int > hash ( 26 ) ;
for ( char c : s1) {
hash[ c - 'a' ] ++ ;
}
for ( char c : s2) {
hash[ c - 'a' ] -- ;
}
for ( int e : hash) {
if ( e > 0 ) {
return false ;
}
}
return true ;
}
存在重复元素
unordered_set< int > hash;
bool containsDuplicate ( vector< int > & nums) {
for ( int e : nums) {
if ( hash. count ( e) > 0 ) {
return true ;
} else {
hash. insert ( e) ;
}
}
return false ;
}
存在重复元素 II
unordered_map< int , int > hash;
bool containsNearbyDuplicate ( vector< int > & nums, int k) {
for ( int i = 0 ; i < nums. size ( ) ; ++ i) {
if ( hash. count ( nums[ i] ) > 0 && i - hash[ nums[ i] ] <= k) {
return true ;
} else {
hash[ nums[ i] ] = i;
}
}
return false ;
}
字母异位词分组
unordered_map< string, vector< string>> hash;
vector< vector< string>> groupAnagrams ( vector< string> & strs) {
for ( string& s : strs) {
string tmp = s;
ranges:: sort ( tmp) ;
if ( hash. count ( tmp) > 0 ) {
hash[ tmp] . push_back ( s) ;
} else {
hash[ tmp] = { s } ;
}
}
vector< vector< string>> ret;
for ( auto & e : hash) {
ret. push_back ( e. second) ;
}
return ret;
}