题目描述
在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
每行二分
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
for( int i = 0 ; i < array.size() ; i++ ){
int len = array[i].size();
int pos = lower_bound(array[i].begin(),array[i].end(),target)-array[i].begin();
if( pos < len && target == array[i][pos] ) return true ;
}
return false;
}
};
题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
从后往前遍历,移动
class Solution {
public:
void replaceSpace(char *str,int length) {
int c = 0 ;
for( int i = 0 ; i < length ; i++ ){
if( str[i] == ' ' ){
c ++ ;
}
}
for( int i = length - 1; i >= 0 ; i-- ){
if( str[i] != ' ' ) str[i+2*c] = str[i] ;
else{
c-- ;
str[i+2*c] = '%';
str[i+2*c+1] = '2';
str[i+2*c+2] = '0';
}
}
}
};
题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
用栈
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int>a;
stack<int>s ;
while( head ){
s.push(head->val) ;
head = head -> next ;
}
int x ;
while( s.size() ){
x = s.top() ;
s.pop() ;
a.push_back(x) ;
}
return a ;
}
};
题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
递归建立二叉树:
每次以前序序列第一个x为根,在中序中找到x,左边的为左子树中序序列,右边的为右子树的中序序列;
再将得到的左,右子树的前序,中序序列分别重复上述过程;
class Solution {
public:
TreeNode* reConstructBinaryTree( vector<int> pre,vector<int> vin ) {
if ( !pre.size() || !vin.size() ) {
return NULL;
}
TreeNode* rt = new TreeNode(pre[0]);
for (int i = 0; i < vin.size(); i++) {
if ( vin[i] == pre[0]) {
//[L,R)
vector<int> p1( pre.begin()+1 , pre.begin()+i+1 ) ;
vector<int> v1( vin.begin() , vin.begin() + i ) ;
rt->left = reConstructBinaryTree( p1 , v1 );
vector<int> p2( pre.begin()+i+1 , pre.end() ) ;
vector<int> v2( vin.begin()+i+1 , vin.end() ) ;
rt->right = reConstructBinaryTree( p2 , v2 );
break;
}
}
return rt;
}
};
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
Push则直接放入stack1
Pop则将stack1中全放入2,再取stack2栈顶
class Solution
{
public:
void push(int node) {
stack1.push(node) ;
}
int pop() {
if( !stack2.size() ){
while( stack1.size() ){
stack2.push(stack1.top()) ;
stack1.pop() ;
}
}
int tmp = stack2.top() ; stack2.pop() ;
return tmp ;
}
private:
stack<int> stack1;
stack<int> stack2;
};
题目描述
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
class Solution {
public:
int minNumberInRotateArray(vector<int> a) {
if( !a.size() ) return 0 ;
sort( a.begin() , a.end() );
return a[0] ;
}
};
题目描述
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
class Solution {
public:
int Fibonacci(int n) {
int a[50] ;
a[0] = 0 ;
a[1] = 1 ;
for( int i = 2 ; i <= 40 ; i++ ){
a[i] = a[i-1] + a[i-2] ;
}
return a[n] ;
}
};
题目描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
递推:f[n] = f[n-1] + f[n-2]
class Solution {
public:
int jumpFloor(int number) {
int n1 = 2 ;
int n2 = 1 ;
int ans = 0 ;
if( number == 1 ) return 1 ;
else if( number == 2 ) return 2 ;
for( int i = 3 ; i <= number ; i++ ){
ans = n2 + n1 ;
n2 = n1 ;
n1 = ans ;
}
return ans ;
}
};
题目描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
方法一:
f[n] = f[n-1] + f[n-2] + … + f[1]
方法二:
f[n] = f[n-1] + f[n-2] + … + f[1]
f[n-1] = f[n-2] + f[n-3] + … + f[1]
相减:f[n] = 2*f[n-1]
故结果为2^(n-1)
class Solution {
public:
int jumpFloorII(int number) {
int ans = 2 ;
if( number == 1 ) return 1 ;
else if( number == 2 ) return 2 ;
int res = 3 ;
for( int i = 3 ; i <= number ; i++ ){
ans = res + 1 ;
if( i != number ) res += ans;
}
return res + 1 ;
}
};
class Solution {
public:
int jumpFloorII(int number) {
return 1<<(number-1);
}
};
题目描述
我们可以用2 * 1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2 * 1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
n = 1 , 一种
n = 2 ,横,竖两种
n = 3,第3列竖着放,用1列,剩 n = 2,2种
第3列横着放,用了2列,剩 n = 1,1种。共3种
… n=k时,只需要管横竖怎么放,故f[k] = f[k-1] + f[k-2]
class Solution {
public:
int rectCover(int n) {
if( !n ) return 0;
if( n == 1 ) return 1;
if( n == 2 ) return 2;
return rectCover( n - 1 ) + rectCover( n - 2 ) ;
}
};
题目描述
输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
方法一:补码和移码关系
方法二:n&(n-1)->将最右边的1变为0
方法三:当做无符号数逻辑右移(补0)(有符号数负数补码右移补1)
int NumberOf1(int n) {
if( !n ) return 0 ;
long long ans = (long long)n ;
int c = 0 ;
if( n < 0 ) ans += (1ll<<32) ; //补码,移码
while( ans ){
if( ans & 1 ) c++ ;
ans >>= 1 ;
}
return c ;
}
class Solution {
public:
int NumberOf1(int n) {
int c = 0 ;
while( n ){
c ++ ;
n &= (n-1); //每次使最右1变为0
}
return c ;
}
};
int NumberOf1(int n) {
int c = 0 ;
unsigned int ans = (unsigned int)n ; // Logical Shift Right (add 0)
while( ans ){
if( ans & 1 ) c ++ ;
ans >>= 1 ;
}
return c ;
}
题目描述
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
保证base和exponent不同时为0
class Solution {
public:
double Power(double a, int b) {
if( !a ) return 0 ;
if( !b ) return 1 ;
double res = 1.0 ;
int c = abs(b) ;
for( int i = 0 ; i < c ; i++ ){
res = 1.0 * res * a ;
}
if( b < 0 ) res = (double)1.0/res ;
return res ;
}
};
题目描述
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
类似插入排序
class Solution {
public:
void reOrderArray(vector<int> &a) {
int len = a.size() ;
for( int i = 0 ; i < len ; i ++ ){
if( !(a[i]&1) ) continue ;
for( int j = i - 1 ; j >= 0 ; j-- ){
if( !(a[j]&1) && (a[j+1]&1) ){
swap(a[j+1],a[j]) ;
}
}
}
}
};
题目描述
输入一个链表,输出该链表中倒数第k个结点。
队列只存储k个值
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindKthToTail(ListNode* Head, unsigned int k) {
if( Head == NULL ) return Head ;
unsigned int c = 0 ;
queue<ListNode*>q ;
while( Head ){
q.push(Head);
if( c < k ) c ++ ;
else q.pop() ;
Head = Head -> next ;
}
return ( c < k ? NULL : q.front() ) ;
}
};
题目描述
输入一个链表,反转链表后,输出新链表的表头。
p 指向x左节点,(初始null)q指向x节点(初始头指针),cur指向x下一节点
遍历一遍,将链表反转
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* head) {
if( head == NULL ) return head ;
ListNode* p = NULL;
ListNode* cur = head -> next ;
ListNode* q = head;
while( cur ){
q -> next = p ;
p = q ;
q = cur ;
cur = cur -> next ;
}
q -> next = p ;
return q ;
}
};
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
归并
设置L指针为新的表头(初始指向H1,H2更小的那个)
遍历H2与H1,比较大小,H2小则插入H1前面;
H2大则移动H1
最后H2不空则链接到后面
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* H1, ListNode* H2){
if( H1 == NULL && H2 == NULL ) return NULL ;
if( H1 == NULL ) return H2 ;
if( H2 == NULL ) return H1 ;
ListNode* pre = new ListNode(-1) ; //pre初始化
ListNode* tmp ;
ListNode* L ;
if( H1 -> val < H2 -> val ){
L = H1 ;
}else L = H2 ;
while( H1 && H2 ){
if( H2 -> val <= H1 -> val ){
tmp = H2 -> next ;
pre -> next = H2 ;
H2 -> next = H1 ;
pre = H2 ;
H2 = tmp ;
}else{
pre = H1 ;
H1 = H1 -> next ;
}
}
if( H2 ){
pre -> next = H2 ;
}
return L ;
}
};
题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
class Solution {
public:
void Mirror(TreeNode *rt) {
if( rt == NULL ) return ;
queue<TreeNode*>q ;
q.push(rt) ;
TreeNode* tmp ;
TreeNode* t ;
while( !q.empty() ){
tmp = q.front() ;
q.pop() ;
t = tmp -> left ;
tmp -> left = tmp -> right;
tmp -> right = t ;
if( tmp -> left ) q.push(tmp -> left);
if( tmp -> right ) q.push(tmp -> right);
}
}
};
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
规律是向右,向下,向左,向上这样循环:
类似bfs那样开个方向数组,map标记走过的坐标
注意不越界,变方向即可
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > v) {
vector<int>res ;
int dir[4][2] = {
{0,1},
{1,0},
{0,-1},
{-1,0}
};
int r = v.size() ;
int c = v[0].size() ;
typedef pair<int,int>P;
map<P,int>vis;
int x = 0 , y = 0 ;
int i = 0 ;
while( x >= 0 && x < r && y >= 0 && y < c && !vis[P(x,y)] ){
res.push_back(v[x][y]) ;
vis[P(x,y)] = 1 ;
while( x + dir[i][0] >= 0 && x + dir[i][0] < r
&& y + dir[i][1] >= 0 && y + dir[i][1] < c
&& !vis[P(x + dir[i][0],y + dir[i][1])] ){
x += dir[i][0] ;
y += dir[i][1] ;
res.push_back(v[x][y]) ;
vis[P(x,y)] = 1 ;
}
i = ( i + 1 ) % 4 ;
x += dir[i][0] ;
y += dir[i][1] ;
}
return res ;
}
};
题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
模拟下入栈出栈过程,一个一个入栈,如果出栈序列==栈顶元素,则一直出栈
class Solution {
public:
bool IsPopOrder(vector<int> a,vector<int> b) {
stack<int>s ;
int tot = 0 ;
for( int i = 0 ; i < a.size() ; i++ ){
s.push(a[i]) ;
while( !s.empty() && s.top() == b[tot] ){ s.pop() ; tot++; }
}
if( s.empty() ) return true ;
return false ;
}
};
题目描述 从上往下打印出二叉树的每个节点,同层节点从左至右打印。
层次遍历
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* rt) {
vector<int> res;
if( rt == NULL ) return res;
queue<TreeNode*>q;
q.push( rt ) ;
while( !q.empty() ){
TreeNode* tmp = q.front() ;
q.pop() ;
res.push_back( tmp -> val ) ;
if( tmp -> left ) q.push( tmp -> left ) ;
if( tmp -> right ) q.push( tmp -> right ) ;
}
return res ;
}
};
题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
方法一:BST中序遍历为有序序列,而中序和后序相当于入栈出栈组合,那么可以判断以中序入栈,能不能得到后序的出栈次序
方法二:递归,后序遍历最后一个元素为根,除去最后一个根,能分为L,R两子树,L子树<根,R子树>根;
判断每个子树是否满足这个性质即可;
class Solution {
public:
bool VerifySquenceOfBST(vector<int> a) {
int len = a.size() ;
if(!len) return false;
std::vector<int> b(a.begin(),a.end());
sort( a.begin() , a.end() ) ;
stack<int>s;
int tot = 0 ;
for( int i = 0 ; i < len ; i++ ){
s.push(a[i]) ;
while( !s.empty() && s.top() == b[tot] ){ tot ++ ; s.pop() ; }
}
if( s.empty() ) return true;
return false ;
}
};
class Solution {
public:
bool f( vector<int>a ){
int len = a.size() ;
if( !len ) return true ;
int mid = 0 ;
while( mid < len && a[mid] < a[len-1] ) mid ++ ;
for( int i = mid ; i < len - 1 ; i++ ){
if( a[i] < a[len-1] ) return false ;
}
return ( f( vector<int> (a.begin(),a.begin()+mid)) &&
f( vector<int> (a.begin()+mid+1,a.end())) ) ;
}
bool VerifySquenceOfBST(vector<int> a) {
if( !a.size() ) return false ;
return f(a) ;
}
};
题目描述
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
class Solution {
public:
vector<vector<int> > res ;
vector<int> a ;
void dfs( TreeNode* rt , int sum , int k ){
//if( rt == NULL ) return ;
if( sum == k ) {
res.push_back(a) ;
return ;
}
if( rt -> left ) {
a.push_back( rt -> left -> val ) ;
dfs( rt -> left , sum + rt -> left -> val , k ) ;
a.pop_back( ) ;
}
if( rt -> right ) {
a.push_back( rt -> left -> val ) ;
dfs( rt -> right , sum + rt -> right -> val , k ) ;
a.pop_back( ) ;
}
}
bool cmp( vector<int> a , vector<int> b ){
return a.size( ) > b.size() ;
}
vector<vector<int> > FindPath(TreeNode* rt,int k) {
if( rt == NULL ) return res ;
a.push_back( rt -> val ) ;
dfs( rt , rt -> val , k ) ;
sort( res.begin() , res.end() , cmp ) ;
return res ;
}
};
题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
class Solution {
public:
TreeNode* Convert(TreeNode* rt) {
if( rt == NULL ) return rt ;
TreeNode* L = NULL ;
TreeNode *pre = rt ;
TreeNode *p = rt ;
TreeNode *last ;
stack<TreeNode*>s ;
while( !s.empty() || p != NULL ){
while( p != NULL ){
s.push(p) ;
p = p -> left ;
}
if( !s.empty() ){
p = s.top() ; s.pop() ;
//cout << p->val << endl;
last = p ;
if( L ){
pre -> right = p ;
p -> left = pre ;
}
pre = p ;
if( L == NULL ) L = p ;
p = p -> right ;
}
}
last -> right = NULL ; //双向链表,不是循环链表= =。
L -> left = NULL ;
return L ;
}
};
题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
输入描述:
输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。
class Solution {
public:
vector<string> Permutation(string str) {
vector<string>res;
int c[50] ;
int len = str.size() ;
if( !len ) return res ;
for( int i = 0 ; i < len ; i++ ){
c[i] = str[i] - 'a';
}
sort( c , c + len ) ;
do{
string tmp ;
for( int i = 0 ; i < len ;i ++ ){
tmp += (char)(c[i] + 'a') ;
}
res.push_back(tmp) ;
}while( next_permutation( c , c + len ) );
return res ;
}
};
题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> a) {
int val ;
int tot = 0 ;
int len = a.size() ;
if( !len ){
return 0 ;
}
for( int i = 0 ; i < len ; i++ ){
if( !tot ){
val = a[i] ;
tot ++ ;
}else{
if( val == a[i] ) tot++ ;
else tot -- ;
}
}
tot = 0 ;
for( int i = 0 ; i < len ; i++ ){
if( a[i] == val ) tot ++ ;
}
return ( ( tot > len / 2 ) ? val : 0 ) ;
}
};
题目描述
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。
class Solution {
public:
vector<int> GetLeastNumbers_Solution(vector<int> a, int k) {
sort( a.begin() , a.end() ) ;
if( a.size() < k ){ a.clear() ; return a ;}
vector<int> res( a.begin() , a.begin() + k ) ;
return res ;
}
};
题目描述
HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子向量的最大和为8(从第0个开始,到第3个为止)。给一个数组,返回它的最大连续子序列的和,你会不会被他忽悠住?(子向量的长度至少是1)
class Solution {
public:
int FindGreatestSumOfSubArray(vector<int> a) {
int len = a.size() ;
int sum = 0 ;
int res = 0 - 0x3f3f3f3f ;
for( int i = 0 ; i < len ; i++ ){
res = max( res , a[i] ) ;
if( sum + a[i] > 0 ){
sum += a[i] ;
res = max( res , sum ) ;
}else{
sum = 0 ;
}
}
return res ;
}
};
题目描述
求出113的整数中1出现的次数,并算出1001300的整数中1出现的次数?为此他特别数了一下1~13中包含1的数字有1、10、11、12、13因此共出现6次,但是对于后面问题他就没辙了。ACMer希望你们帮帮他,并把问题更加普遍化,可以很快的求出任意非负整数区间中1出现的次数(从1 到 n 中1出现的次数)。
分别统计个位,十位,百位上1的个数,归纳出通式;
个位:每隔10出现一次1,如:1 ,11,21…
先统计出整数个10的个数 n / 10 * 10 ,
再计算多余的 k = n%10,
如果k > 1,那么结果可再+1,
如果k < 1, 那么结果不变;
十位:每隔100出现一次1,如10,110,210…
先统计出整数个100的个数 n / 100 * 100 ,
再计算多余的 k = n%100,
如果k > 19,那么结果可再+10个,
如果k < 10, 那么结果不变(对十位未贡献1)
10-19中间则贡献k-10+1个1
百位:每隔1000出现一次1,如1100,2100,3100…
…
归纳出通式:
d = 10 ^ x ;
k = n % d ;
x位上1的数量 : count(x) = n / d * d + tmp ;
if( k > 2 * i - 1 ) tmp = i ;
if( k < i ) tmp = 0 ;
tmp = k - i + 1 ;
[x = 1 , 2 , 3 .....],i = d / 10 , (个位数量级1,十位10.....)
class Solution {
public:
int NumberOf1Between1AndN_Solution(int n){
int res = 0 ;
int k , tmp ;
for( int i = 1 ; i <= n ; i *= 10 ){
long long d = 10 * i ;
k = n % ( i * 10 ) ;
if( k > 2 * i - 1 ) tmp = i ;
else if( k < i ) tmp = 0 ;
else tmp = k - i + 1 ;
res += 1LL * ( n / d ) * i + tmp ;
}
return res ;
}
};
题目描述
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
对于数字A,B。 AB组成的数字与BA组成的数字大小定义为A,B之间新的大小关系,由于A,B在int范围内,AB可能超过int范围。故先转为字符串比较大小。
class Solution {
public:
static bool cmp( string a , string b ){
string sa = a + b ;
string sb = b + a ;
return sa < sb ;
}
string PrintMinNumber(vector<int> a){
vector<string> s ;
int len = a.size() ;
if( len <= 0 ) return "" ;
stringstream ss ;
for( int i = 0 ; i < len ; i++ ){
ss << a[i] ;
s.push_back( ss.str() ) ;
ss.str("") ;
}
string res = "" ;
sort( s.begin() , s.end() , cmp ) ;
for( int i = 0 ; i < len ; i++ ){
res += s[i] ;
}
return res ;
}
};
题目描述
把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
class Solution {
public:
int GetUglyNumber_Solution(int n) {
if( !n ) return 0 ;
set<long long> s ;
s.insert(1) ;
for( int i = 1 ; i < n ; i++ ){
long long tmp = *s.begin() ;
s.erase(s.begin()) ;
s.insert(tmp*2LL);
s.insert(tmp*3LL);
s.insert(tmp*5LL);
}
return *s.begin() ;
}
};
题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
class Solution {
public:
map<char,int>mp;
map<char,int>pos;
int FirstNotRepeatingChar(string s) {
int len = s.size() ;
if( !len ) return -1 ;
for( int i = 0 ; i < len ; i ++ ){
if( !mp[s[i]] ) pos[s[i]] = i ;
mp[s[i]] ++ ;
}
int res = 10001 ;
for( int i = 0 ; i < len ; i++ ){
if( mp[s[i]] == 1 ){
res = min( pos[s[i]] , res ) ;
}
}
return ( res == 10001 ? -1 : res ) ;
}
};
题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
输入描述:
题目保证输入的数组中没有的相同的数字
数据范围:
对于%50的数据,size<=10^4
对于%75的数据,size<=10^5
对于%100的数据,size<=2*10^5
class Solution {
public:
struct Node{
int pos;
int val;
}node[200005];
int flect[200005];
int c[200005];
int n;
static bool cmp(Node a,Node b){
return a.val<b.val;
}
int lowbit(int x){
return x&(-x);
}
void update(int value,int site){
while(site<=n){
c[site] += value;
site += lowbit(site);
}
}
int getsum(int i){
int sum = 0;
while(i>=1){
sum += c[i];
i -= lowbit(i);
}
return sum;
}
int InversePairs(vector<int> data) {
int ans = 0 ;
n = data.size() ;
memset(node,0,sizeof(node));
memset(flect,0,sizeof(flect));
memset(c,0,sizeof(c));
for(int i=1;i<=n;i++){
node[i].val = data[i-1];
node[i].pos = i;
}
sort(node+1,node+n+1,cmp);
for(int i=1;i<=n;i++){
flect[node[i].pos] = i;
}
for(int i=1;i<=n;i++){
update(1,flect[i]);
ans += (i-getsum(flect[i]));
ans %= 1000000007 ;
}
return ans % 1000000007;
}
};
题目描述
输入两个链表,找出它们的第一个公共结点。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public: // 右对齐
ListNode* FindFirstCommonNode( ListNode* L1, ListNode* L2) {
if( L1 == NULL || L2 == NULL ) return NULL ;
ListNode* p = L1 ;
ListNode* q = L2 ;
int la = 0 , lb = 0 ;
while( p ){
la++ ;
p = p -> next ;
}
while( q ){
lb++ ;
q = q -> next ;
}
int t = abs(la-lb) ;
if( la > lb ) while( t-- ) L1 = L1 -> next ;
else while( t-- ) L2 = L2 -> next ;
while( L1 ){
if( L1 == L2 ){
return L1 ;
}
L1 = L1 -> next ;
L2 = L2 -> next ;
}
return NULL ;
}
};
题目描述
统计一个数字在排序数组中出现的次数。
class Solution {
public:
int GetNumberOfK(vector<int> a ,int k) {
vector<int>::iterator it = lower_bound( a.begin() , a.end() , k ) ;
if( it == a.end() ) return 0 ;
int st = it - a.begin() ;
int ed = upper_bound( a.begin() , a.end() , k ) - a.begin() ;
return ed - st ;
}
};
题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
int res = 1 ;
/*
void dfs( TreeNode* rt , int depth ){
res = max( res , depth ) ;
if( rt -> left ) dfs( rt -> left , depth + 1 ) ;
if( rt -> right ) dfs( rt -> right , depth + 1 ) ;
}
*/
int getHigh( TreeNode* rt ){
if( rt == NULL ) return 0 ;
return max( getHigh( rt -> left ) , getHigh( rt -> right ) ) + 1 ;
}
int TreeDepth(TreeNode* rt){
if( rt == NULL ) return 0 ;
return getHigh( rt ) ;
//return res ;
}
};
题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
class Solution {
public:
int getHigh( TreeNode* rt ){
if( rt == NULL ) return 0 ;
int lh = getHigh( rt -> left ) ;
int rh = getHigh( rt -> right ) ;
if( lh == -1 || rh == -1 || abs( lh - rh ) > 1 ) return -1 ;
return max( lh ,rh ) + 1 ;
}
bool IsBalanced_Solution( TreeNode* rt ){
return ( getHigh( rt ) != -1 ) ;
}
};
题目描述
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
class Solution {
public:
void FindNumsAppearOnce( vector<int> a,int* num1,int *num2) {
int len = a.size() ;
int f = -1 ;
sort( a.begin() , a.end() ) ;
a.push_back( 0x3f3f3f3f ) ;
for( int i = 0 ; i < len ; i++ ){
if( f == 2 ) break ;
if( a[i] == a[i+1] ){
i += 1 ;
}else{
if( f == -1 ) { num1[0] = a[i] ; f = 1 ; }
else { num2[0] = a[i] ; f = 2 ; }
}
}
return ;
}
};
题目描述
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
输出描述:
输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
利用等差数列求和公式,枚举,根号级别的复杂度
class Solution {
public:
static bool cmp( vector<int>a , vector<int>b ){
return a[0] < b[0] ;
}
vector<vector<int> > FindContinuousSequence(int S) {
int a1 ;
vector<int> t;
vector<vector<int> >res ;
for( int n = 2 ; ; n++ ){
if( n * ( n - 1 ) / 2 >= S ) break ;
int tmp = S - 1LL * n * ( n - 1 ) / 2 ;
if( !( tmp % n ) ){
a1 = tmp / n ;
if( a1 <= 0 ) break ;
for( int i = 0 ; i < n ; i++ ){
t.push_back(a1+i) ;
}
res.push_back(t) ;
t.clear() ;
}
}
sort( res.begin() , res.end() , cmp ) ;
return res ;
}
};
题目描述
输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
输出描述:
对应每个测试案例,输出两个数,小的先输出。
class Solution {
public:
vector<int> FindNumbersWithSum(vector<int> a,int S) {
vector<int>res ;
int len = a.size() ;
if( len < 2 ) return res ;
long long ans = 0x3f3f3f3f ;
for( int i = 0 ; i < len - 1 ; i++ ){
vector<int>::iterator it = lower_bound( a.begin() + i + 1 , a.end() , S - a[i] ) ;
if( it != a.end() ){
if( *it != S - a[i] ) continue ;
long long t = 1LL * a[i] * ( S - a[i] ) ;
if( ans > t ){
if( ans != 0x3f3f3f3f ) res.clear() ;
res.push_back(a[i]) ;
res.push_back(S-a[i]) ;
ans = t ;
}
}
}
return res ;
}
};
题目描述
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
class Solution {
public:
string LeftRotateString(string str, int n) {
if( !n ) return str ;
int len = str.size() ;
if( !len ) return str ;
n = n % len ;
string res = "" ;
for( int i = n ; i < len ; i++ ) res += str[i] ;
for( int i = 0 ; i < n ; i++ ) res += str[i] ;
return res ;
}
};
题目描述
牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?
class Solution {
public: // 1
void Reverse( char* st , char* ed ){
if( st == NULL || ed == NULL ) return ;
while( st < ed ){
char tmp = *st ;
*st = *ed ;
*ed = tmp ;
st ++ ; ed -- ;
}
}
char s[10000] ;
string ReverseSentence(string str) {
if( !str.size() ) return "" ;
strcpy( s , str.c_str() ) ;
char* st = s ;
char* ed = s ;
while( *ed != '\0' ) ed ++ ;
ed -- ;
Reverse( st , ed ) ;
st = s ; ed = s ;
while( *st != '\0' ){
if( *st == ' ' ){
st ++ ;
ed ++ ;
}else if( *ed == '\0' || *ed == ' ' ){
Reverse( st , --ed ) ;
st = ++ed ;
}else{
ed ++ ;
}
}
string res(s) ;
return res;
}
};
题目描述
每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0…m-1报数…这样下去…直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!_)。请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1)
如果没有小朋友,请返回-1
class Solution {
public:
int LastRemaining_Solution(int n, int m){
if( !n ) return -1 ;
int s = 0 ;
for (int i = 2; i <= n; i++){
s = (s + m) % i;
}
return s ;
}
};
题目描述
求1+2+3+…+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
class Solution {
public:
int mul( int a , int b ){
int sum = 0;
( a & 1 )&&( sum += b ) ;
a >>= 1 ; b <<= 1 ;
a && ( sum += mul( a , b ) ) ;
return sum ;
}
int sum = 0 ;
int Sum_Solution(int n) {
// return mul( n , n + 1 ) >> 1 ;
bool tmp = ( n && Sum_Solution( n - 1 ) ) ;
sum += n ;
return sum ;
}
};
题目描述
写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。
class Solution {
public:
/*
在计组中,半加器、全加器中:
两个二进制的相加结果是用一个异或门实现的;
两个二进制的进位结果是用一个与门来实现的。
进位为时,当前运算结果为最终结果
*/
int Add(int num1, int num2){
int res , carry ;
do{
res = ( num1 ^ num2 ) ;
carry = ( num1 & num2 ) << 1 ;
num1 = res ;
num2 = carry ;
}while( carry ) ;
return res ;
}
};
题目描述
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
输入描述:
输入一个字符串,包括数字字母符号,可以为空
输出描述:
如果是合法的数值表达则返回该数字,否则返回0
class Solution {
public:
char * strim(char *str){
char *end , *sp , *ep ;
int len;
sp = str;
end = str + strlen(str) - 1 ;
ep = end;
while( sp <= end && (*sp) == ' ' ) sp++ ;
while( ep >= sp && (*ep) == ' ' ) ep-- ;
len = ( ep < sp ) ? 0 : ep - sp + 1 ;
sp[len] = '\0' ;
return sp ;
}
char str[10005] ;
long long MAX = 2147483647LL;
long long MIN = 2147483648LL ;
int StrToInt( string t ) {
strcpy( str , t.c_str() ) ;
char* s = strim( str ) ;
int len = strlen(s) ;
if( !len ) return 0 ;
for( int i = 1 ; i < len ; i++ ){
if( !( s[i] >= '0' && s[i] <= '9' ) ) return 0 ;
}
long long base = 1 ;
long long sum = 0 ;
if( s[0] == '+' || s[0] == '-' ){
for( int i = len - 1 ; i > 0 ; i-- ){
sum += 1LL * (long long)( s[i] -'0' ) * base ;
base *= 10 ;
}
if( s[0] == '-' ) { if( sum > MIN ) return 0 ; return 0-sum ; }
if( sum > MAX ) return 0 ;
return sum ;
}else if( s[0] >= '0' && s[0] <= '9' ){
for( int i = len - 1 ; i >= 0 ; i-- ){
sum += 1LL * ( s[i] -'0' ) * base ;
base *= 10 ;
}
if( sum > MAX ) return 0 ;
return sum ;
}else return 0 ;
}
};
题目描述
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
class Solution {
public:
// Parameters:
// a: an array of integers
// len: the length of array numbers
// b: (Output) the duplicated number in the array number
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
bool duplicate(int a[], int len, int* b) {
for( int i = 0 ; i < len ; i++ ){
while( a[i] != i ){
if( a[i] == a[a[i]] ){
b[0] = a[i] ;
return true ;
}
swap( a[i] , a[a[i]] ) ;
}
}
return false ;
}
};
题目描述
给定一个数组A[0,1,…,n-1],请构建一个数组B[0,1,…,n-1],其中B中的元素B[i]=A[0]A[1]…*A[i-1]A[i+1]…*A[n-1]。不能使用除法。
class Solution {
public:
vector<int> multiply(const vector<int>& A) {
int len = A.size();
vector<int>B(len);
int res = 1 ;
for(int i=0;i<len;i++){
B[i] = res;
res *= A[i];
}
res = 1 ;
for(int i = len-1 ; i >= 0 ; i-- ){
B[i] *= res;
res *= A[i];
}
return B;
}
};
题目描述
请实现一个函数用来匹配包括’.‘和’‘的正则表达式。模式中的字符’.‘表示任意一个字符,而’'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"abaca"匹配,但是与"aa.a"和"ab*a"均不匹配
关键是对 ‘*’ 的处理,分为三种:
一:’ * ‘前的字母匹配0次,此时str不动,pattern后移2步;
一:’ * ‘前的字母匹配1次,此时str+1,pattern后移2步;
一:’ * '前的字母匹配多次;此时str+1,pattern不动;
class Solution {
public:
bool matchCore( char* str , char* pattern ){
if( *str == '\0' && *pattern == '\0' ) return true ;
if( *str != '\0' && *pattern == '\0' ) return false ;
if( *( pattern + 1 ) == '*' ){
if( *pattern == *str || ( *pattern == '.' && *str != '\0' ) ){
return ( matchCore( str + 1 , pattern + 2 ) //1
|| matchCore( str + 1 , pattern ) //multi
|| matchCore( str , pattern + 2 ) //0
) ;
}else return matchCore( str , pattern + 2 ) ; // 0
}
if( *pattern == *str || ( *pattern == '.' && *str != '\0' ) ){
return matchCore( str + 1 , pattern + 1 ) ;
}
return false ;
}
bool match(char* str, char* pattern){
if( str == NULL || pattern == NULL ) return false ;
return matchCore( str , pattern ) ;
}
};
题目描述
请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100",“5e2”,"-123",“3.1416"和”-1E-16"都表示数值。 但是"12e",“1a3.14”,“1.2.3”,"±5"和"12e+4.3"都不是。
没有其他特殊符号,是考察字符串模式匹配
class Solution {
public:
// 满足 A[.[B]][E|eC]
//A,B至少有其一
//A,C开头可能有符号,B开头无符号
bool judgeUnInteger( char** s ){//judge B
char* st = *s ;
while( **s != '\0' && **s >= '0' && **s <= '9' ) ++(*s) ;
return *s > st ;
}
bool judgeInteger( char** s ){ //judge A and C
if( **s == '+' || **s == '-' ) ++(*s) ;
return judgeUnInteger(s) ;
}
bool isNumeric(char* s){
if( s == NULL ) return false ;
bool res = judgeInteger(&s) ; // A
if( *s == '.' ){
++s ;
res = judgeUnInteger(&s) || res ; // B *次序,短路
}
if( *s == 'E' || *s == 'e' ){
++s ;
res = res && judgeInteger(&s) ; // C
}
return res && *s == '\0' ;
}
};
题目描述
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
标记出现次序,次数,注意构造函数初始化数组就行
class Solution
{
private:
int a[256] ;
int idx[256] ;
int id ;
public:
Solution(){
memset( a , 0 ,sizeof(a) ) ;
id = 0 ;
memset( idx , 0 , sizeof(idx) ) ;
}
//Insert one char from stringstream
void Insert(char ch){
if( !a[ch] ) { a[ch] = 1 ; idx[ch] = ++id ; }
else a[ch] = -1 ;
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce(){
char res = '#' ;
int minu = 0x3f3f3f3f ;
for( int i = 0 ; i < 256 ; i++ ){
if( a[i] == 1 ){
if( minu > idx[i] ){
minu = idx[i] ;
res = (char)(i) ;
}
}
}
return res ;
}
};
题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* getNode( ListNode* node , ListNode* H ){
ListNode* tmp = node ;
int c = 1 ;
while( tmp -> next != node ){
c ++ ;
tmp = tmp -> next ;
}
ListNode* p1 = H ;
ListNode* p2 = H ;
while( c-- ){ // p1 , p2
p1 = p1 -> next ; //p1
}
while( p1 != p2 ){
p1 = p1 -> next ;
p2 = p2 -> next ;
}
return p1 ;
}
ListNode* getOneNode( ListNode* H ){
ListNode* slow = H ;
ListNode* fast = slow -> next ;// fast and slow point .
while( slow && fast ){
if( slow == fast ){
return fast ;
}
slow = slow -> next ;
fast = fast -> next ; // slow : 1v
if( fast ) fast = fast -> next ; // fast : 2v
}
return NULL;
}
ListNode* EntryNodeOfLoop(ListNode* H){
if( H == NULL ) return NULL ;
ListNode* Node = getOneNode( H ) ; //get one node of the ring.
if( Node == NULL ) return NULL ;
return getNode( Node , H ) ; //get the first node of the ring.
}
};
题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
/*
ListNode **p = pHead用于修改结点
p最初指向头结点,当头结点重复时可以通过*p直接修改头结点
不重复时可以通过p = &(xxx)修改其指向的结点*/
class Solution {//1
public:
ListNode* deleteDuplication(ListNode* H){
if( !H ) return NULL ;
ListNode* tmp ;
int f = 0 ;
ListNode** p = &H ;
while( *p ){
f = 0 ;
tmp = (*p) -> next ;
while( tmp && tmp -> val == (*p) -> val ){
f = 1 ;
tmp = tmp -> next ;
}
if( f ){//结点重复,指向后面第一个不同节点
*p = tmp ;
}else{
p = &((*p)->next) ;
}
}
return H ;
}
};
题目描述
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
一:nt 节点有右子树,那么下一节点就是右子树最左节点;
二:nt节点没有右子树,设nt_parent为nt双亲节点;
① 若nt节点是nt_parent节点的左孩子,那么下一节点就是nt_parent;
②若nt节点是nt_parent节点的右孩子,说明以 nt_parent 为根的子树已经访问完毕(nt无右子树),故下一节点应为 nt_parent的祖先节点x的父节点x_parent,且x为x_parent的左子树。
/*
struct TreeLinkNode {
int val;
struct TreeLinkNode *left;
struct TreeLinkNode *right;
struct TreeLinkNode *next;
TreeLinkNode(int x) :val(x), left(NULL), right(NULL), next(NULL) {
}
};
*/
class Solution {
public:
TreeLinkNode* GetNext(TreeLinkNode* nt){
TreeLinkNode* res ;
if( nt == NULL ) return NULL ;
if( nt -> right ){
nt = nt -> right ;
while( nt -> left ) nt = nt -> left ;
res = nt ;
}else{
if( nt -> next == NULL ) res = NULL ;
else{
if( nt -> next -> left == nt ) res = nt -> next ;
else{
TreeLinkNode* p = nt ;
TreeLinkNode* pParent = p -> next ;
while( pParent && p == pParent -> right ){
p = pParent ;
pParent = pParent -> next ;
}
res = pParent ;
}
}
}
return res ;
}
};
建树等完整操作如下:
#include <bits/stdc++.h>
using namespace std;
struct TreeLinkNode {
int val;
struct TreeLinkNode *left;
struct TreeLinkNode *right;
struct TreeLinkNode *next;
TreeLinkNode(int x) :val(x), left(NULL), right(NULL), next(NULL) {}
};
int x ;
TreeLinkNode* getRoot( TreeLinkNode* nt ){
while( nt -> next ) nt = nt -> next ;
return nt ;
}
TreeLinkNode* GetNext(TreeLinkNode* nt){
TreeLinkNode* res ;
if( nt == NULL ) return NULL ;
if( nt -> right ){
nt = nt -> right ;
while( nt -> left ) nt = nt -> left ;
res = nt ;
}else{
if( nt -> next == NULL ) res = NULL ;
else{
if( nt -> next -> left == nt ) res = nt -> next ;
else{
TreeLinkNode* p = nt ;
TreeLinkNode* pParent = p -> next ;
while( pParent && p == pParent -> right ){
p = pParent ;
pParent = pParent -> next ;
}
res = pParent ;
}
}
}
return res ;
}
TreeLinkNode* Build( TreeLinkNode* rt , TreeLinkNode* pre ){
cin >> x ;
if( x == -1 ) return NULL ;
rt = new TreeLinkNode(x) ;
rt -> left = Build( rt -> left , rt ) ;
rt -> right = Build( rt -> right , rt ) ;
rt -> next = pre ;
return rt ;
}
int main(){
TreeLinkNode* rt = NULL ;
rt = Build(rt,NULL) ;
TreeLinkNode* nt = rt -> left -> right -> right ;
TreeLinkNode* rs = GetNext( nt ) ;
if( rs == NULL ) cout << "s" << endl;
else cout << rs -> val << endl;
}
//1 2 -1 3 -1 4 -1 -1 -1
//outPut :1
题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
bool checkMirror( TreeNode* l , TreeNode* r ){
if( l == NULL && r == NULL ) return true ;
if( l == NULL || r == NULL ) return false ;
if( l -> val == r -> val ) return checkMirror( l -> left , r -> right ) && checkMirror( l -> right , r -> left ) ;
return false ;
}
bool isSymmetrical(TreeNode* rt){
if( rt == NULL ) return true ;
return checkMirror(rt->left ,rt->right) ;
}
};
题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* rt) {
vector<vector<int> >res ;
if( rt == NULL ) return res ;
int c = 1 ;
queue<TreeNode*>q;
q.push(rt) ;
stack<int>s ;
queue<int>b ;
vector<int>t ;
int lev = 0 ;
while( !q.empty() ){
int k = 0 ;
while( c-- ){
TreeNode* tmp = q.front() ; q.pop() ;
if( lev % 2 == 0 ){
b.push(tmp->val) ;
}else s.push(tmp->val) ;
if( tmp -> left ){
q.push( tmp -> left ) ; k ++ ;
}
if( tmp -> right ){
q.push( tmp -> right ) ; k ++ ;
}
}
if( lev % 2 == 0 ){
while( !b.empty() ){
t.push_back(b.front()) ; b.pop() ;
}
}else{
while( !s.empty() ){
t.push_back(s.top()) ; s.pop() ;
}
}
res.push_back(t) ;
t.clear() ;
c = k ;
lev ++ ;
}
return res ;
}
};
题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* rt) {
vector<vector<int> >res ;
if( rt == NULL ) return res ;
int c = 1 ;
queue<TreeNode*>q;
q.push(rt) ;
vector<int>t ;
int lev = 0 ;
while( !q.empty() ){
int k = 0 ;
while( c-- ){
TreeNode* tmp = q.front() ; q.pop() ;
t.push_back(tmp->val) ;
if( tmp -> left ){
q.push( tmp -> left ) ; k ++ ;
}
if( tmp -> right ){
q.push( tmp -> right ) ; k ++ ;
}
}
res.push_back(t) ;
t.clear() ;
c = k ;
}
return res ;
}
};
题目描述
请实现两个函数,分别用来序列化和反序列化二叉树
二叉树的序列化是指:把一棵二叉树按照某种遍历方式的结果以某种格式保存为字符串,从而使得内存中建立起来的二叉树可以持久保存。序列化可以基于先序、中序、后序、层序的二叉树遍历方式来进行修改,序列化的结果是一个字符串,序列化时通过 某种符号表示空节点(#),以 ! 表示一个结点值的结束(value!)。
二叉树的反序列化是指:根据某种遍历顺序得到的序列化字符串结果str,重构二叉树。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
string s = "" ;
void preOrder( TreeNode* rt ){
stringstream ss ;
if( rt == NULL ) { s += '#' ; return ; }
ss << ( rt -> val ) ;
string t ; ss >> t ;
s += t ;
s += "!" ;
ss.str("") ;
preOrder( rt -> left ) ;
preOrder( rt -> right ) ;
}
char* Serialize(TreeNode *rt) {
preOrder(rt) ;
char t[10000] ;
strcpy( t , s.c_str() ) ;
char* p = t ;
return p ;
}
vector<int>sq ;
int tot = -1 ;
TreeNode* reBuild( TreeNode* rt ){
tot ++ ;
if( sq[tot] == -1 ) rt = NULL ;
else{
rt = new TreeNode(sq[tot]) ;
rt -> left = reBuild( rt -> left ) ;
rt -> right = reBuild( rt -> right ) ;
}
return rt ;
}
TreeNode* Deserialize(char *str) {
int len = strlen(str) ;
string tmp = "" ;
for( int i = 0 ; i < len ; i++ ){
if( str[i] == '!' ){
sq.push_back( atoi( tmp.c_str() ) );
tmp = "" ;
}else if( str[i] == '#' ){
sq.push_back(-1) ;
}else tmp += str[i] ;
}
TreeNode* rt = NULL ;
rt = reBuild( rt ) ;
return rt ;
}
};
题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<TreeNode*> res ;
void InOrder( TreeNode* rt ){
if( rt == NULL ) return ;
InOrder( rt -> left ) ;
res.push_back( rt ) ;
InOrder( rt -> right ) ;
}
TreeNode* KthNode(TreeNode* rt, int k){
if( rt == NULL || !k ) return NULL ;
InOrder( rt ) ;
if( k > (int)res.size() ) return NULL ;
return res[k-1] ;
}
};
题目描述(❤)
如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。
思路:建立一个最大堆(N个元素),最小堆(N个<总数偶数>或N+1个元素<总数奇数>),最大堆维护小于中位数的元素,最小堆维护大于中位数的元素,最小堆的最小元素(堆顶)比最大堆的堆顶元素大;
每次插入数值时,若最大最小堆数目相同,插入最小堆,
若不同,插入最大堆;
插入数据时要考虑:如果将元素num插入最小堆时,若num小于最大堆的堆顶,则先将num插入最大堆,随后将最大堆堆顶插入最小堆,保证最小堆的最小元素(堆顶)比最大堆的堆顶元素大;
vector与less()结合模拟最大堆;
vector与greater()结合模拟最小堆;
class Solution {
public:
void Insert(int num) {
if( ( ( minu.size() + maxn.size() ) & 1 ) == 0 ) {
if( maxn.size() && num < maxn[0] ) {
maxn.push_back(num);
push_heap( maxn.begin() , maxn.end() , less<int>() ) ;
num = maxn[0] ;
pop_heap( maxn.begin() , maxn.end() , less<int>() ) ;
maxn.pop_back() ;
}
minu.push_back(num);
push_heap( minu.begin() , minu.end() , greater<int>() );
} else {
if( minu.size() && num > minu[0] ) {
minu.push_back(num);
push_heap( minu.begin() , minu.end() , greater<int>() );
num = minu[0] ;
pop_heap( minu.begin() , minu.end() , greater<int>() ) ;
minu.pop_back();
}
maxn.push_back(num) ;
push_heap( maxn.begin() , maxn.end() , less<int>() );
}
}
double GetMedian() {
int size = minu.size() + maxn.size() ;
if( size & 1 ) return minu[0] ;
else return ( minu[0] + maxn[0] ) / 2.0 ;
}
private:
vector<int>minu;
vector<int>maxn;
} ;
题目描述
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
class Solution {
public:
map<int,int>mp ;
set<int>s ;
vector<int> maxInWindows(const vector<int>& a, unsigned int n){
vector<int>res ;
int len = a.size() ;
if( !n || !len || n > len ) return res ;
int st = 0 , ed = min( n - 1 , (unsigned int)len ) ;
for( int i = st ; i <= ed ; i++ ) { s.insert(a[i]) ; mp[a[i]]++ ; }
res.push_back( *( --s.end() ) ) ;
while( ed < len - 1 && st <= ed ){
if( !( --mp[a[st]] ) && *(--s.end()) == a[st] ) s.erase(--s.end()) ;
st ++ ;
ed ++ ;
mp[a[ed]] ++ ;
s.insert( a[ed] ) ;
res.push_back(*(--s.end())) ;
}
return res ;
}
};
题目描述
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
class Solution {
public:
char G[3000][3000] ;
int res = 0 ;
int vis[3000][3000] ;
int dir[4][2] = {
{ 1 , 0 } ,
{ 0 , 1 } ,
{ -1 , 0 } ,
{ 0 , -1 } ,
};
void dfs( int x , int y , int d , int k ,int r, int c , char* s ){
if( res ) return ;
if( d == k ){
res = 1 ; return ;
}
for( int i = 0 ; i < 4 ; i++ ){
int xx = x + dir[i][0] , yy = y + dir[i][1] ;
if( xx < 0 || xx >= r || yy < 0 || yy >= c || vis[xx][yy] || G[xx][yy] != s[d] ) continue ;
vis[xx][yy] = 1 ;
dfs( xx , yy , d + 1 , k , r , c , s ) ;
vis[xx][yy] = 0 ;
}
}
bool hasPath(char* m, int r, int c, char* s){
if( s == NULL || m == NULL || r < 1 || c < 1 ) return false ;
for( int i = 0 ; i < r ; i ++ ){
for( int j = 0 ; j < c ; j++ ){
G[i][j] = m[i*c+j] ;
}
}
int len = strlen(s) ;
for( int i = 0 ; i < r ; i++ ){
for( int j = 0 ; j < c ; j++ ){
if( G[i][j] == s[0] ){
vis[i][j] = 1 ;
dfs( i , j , 1 , len , r , c , s ) ;
vis[i][j] = 0 ;
}
if( res ) return true ;
}
}
return false ;
}
};
题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
class Solution {
public:
int vis[3000][3000] ;
int mark[3000][3000] ; //wo cao , multi group input,remember clear them.
int dir[4][2] = {
{ 1 , 0 } ,
{ 0 , 1 } ,
{ -1 , 0 } ,
{ 0 , -1 } ,
};
int sum( int n ){
int ans = 0 ;
while( n ){
ans += ( n % 10 ) ;
n /= 10 ;
}
return ans ;
}
void dfs( int x , int y , int r, int c ){
mark[x][y] = 1 ;
for( int i = 0 ; i < 4 ; i++ ){
int xx = x + dir[i][0] , yy = y + dir[i][1] ;
if( xx < 0 || xx >= r || yy < 0 || yy >= c || vis[xx][yy] ) continue ;
vis[xx][yy] = 1 ;
dfs( xx , yy , r , c ) ;
}
}
int movingCount(int k, int r, int c){
if( k <= 0 || r <= 0 || c <= 0 ) return 0 ;
for( int i = 0 ; i < r ; i++ ){
for( int j = 0; j < c ; j++ ){
if( sum(i) + sum(j) > k ) vis[i][j] = 1 ;
else vis[i][j] = 0 ;
mark[i][j] = 0 ;
}
}
vis[0][0] = 1 ;
dfs( 0 , 0 , r , c ) ;
int res = 0 ;
for( int i = 0 ; i < r ; i++ ){
for( int j = 0; j < c ; j++ ){
if( mark[i][j] ) res ++ ;
}
}
return res ;
}
};
题目描述❤
给你一根长度为n的绳子,请把绳子剪成整数长的m段(m、n都是整数,n>1并且m>1),每段绳子的长度记为k[0],k[1],…,k[m]。请问k[0]xk[1]x…xk[m]可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。
输入描述:
输入一个数n,意义见题面。(2 <= n <= 60)
输出描述:
输出答案。
class Solution {
public:
int dp[65] ;
int cutRope(int n) {
dp[0] = 0 ;
dp[1] = 1 ;
for( int i = 2 ; i <= n ; i ++ ){
dp[i] = ( i == n ? 1 : i ) ; //不能不被分割
for( int j = 1 ; j < i ; j ++ ){
dp[i] = max( dp[i] , dp[j] * dp[i-j] ) ;
}
}
return dp[n] ;
}
};