JZ1 二维数组中的查找
class Solution {
public :
bool Find ( int target, vector< vector< int > > array) {
if ( array. empty ( ) ) return false ;
int m = array. size ( ) , n = array[ 0 ] . size ( ) - 1 ;
int index = 0 ;
while ( index < m && n >= 0 ) {
if ( array[ index] [ n] > target) {
n-- ;
}
else if ( array[ index] [ n] < target) {
index++ ;
}
else return true ;
}
return false ;
}
} ;
JZ2 替换空格
class Solution {
public :
string replaceSpace ( string s) {
string ans;
for ( auto & c: s) {
if ( c == ' ' ) ans+= "%20" ;
else ans+= c;
}
return ans;
}
} ;
JZ3 从尾到头打印链表
class Solution {
public :
vector< int > printListFromTailToHead ( ListNode* head) {
vector< int > ret;
while ( head) {
ret. push_back ( head-> val) ;
head = head-> next;
}
std:: reverse ( ret. begin ( ) , ret. end ( ) ) ;
return ret;
}
} ;
JZ4 重建二叉树
class Solution {
public :
TreeNode* rebuild ( vector< int > & pre, int pre_left, int pre_right, vector< int > & vin, int vin_left, int vin_right) {
if ( pre_left > pre_right) return nullptr ;
TreeNode* root = new TreeNode ( pre[ pre_left] ) ;
int root_index = vin_left;
while ( root_index < vin_right && vin[ root_index] != pre[ pre_left] ) {
root_index++ ;
}
root-> left = rebuild ( pre, pre_left+ 1 , pre_left+ root_index- vin_left, vin, vin_left, root_index- 1 ) ;
root-> right = rebuild ( pre, pre_left+ root_index- vin_left+ 1 , pre_right, vin, root_index+ 1 , vin_right) ;
return root;
}
TreeNode* reConstructBinaryTree ( vector< int > pre, vector< int > vin) {
return rebuild ( pre, 0 , pre. size ( ) - 1 , vin, 0 , vin. size ( ) - 1 ) ;
}
} ;
JZ5 用两个栈实现队列
class Solution
{
public :
void push ( int node) {
stack1. push ( node) ;
}
int pop ( ) {
if ( stack2. empty ( ) ) {
while ( ! stack1. empty ( ) ) {
stack2. push ( stack1. top ( ) ) ;
stack1. pop ( ) ;
}
}
int ans = stack2. top ( ) ;
stack2. pop ( ) ;
return ans;
}
private :
stack< int > stack1;
stack< int > stack2;
} ;