题目来自于:http://blog.csdn.net/v_JULY_v/article/details/6057286
1.把二元查找树转变成排序的双向链表(树)
struct Node
{
int val;
Node *left,*right;
Node(int x):val(x),left(NULL),right(NULL){}
};
void inorderTraversal(Node *root,Node *&tail)
{
if(root)
{
inorderTraversal(root->left,tail);
tail->right=root;
root->left=tail;
tail=root;
inorderTraversal(root->right,tail);
}
}
Node *convert(Node *root)
{
Node dummy(-1);
Node *tail=&dummy;
inorderTraversal(root,tail);
return dummy.right;
}
2.设计包含min函数的栈(栈)
class stack
{
public:
void push(int);
void pop();
int min();
private:
vector<int> value,minValue;
};
void stack::push(int x)
{
value.push_back(x);
if(minValue.size()==0)minValue.push_back(x);
else
{
if(x<minValue.back())minValue.push_back(x);
else minValue.push_back(minValue.back());
}
}
void stack::pop()
{
value.pop_back();
minValue.pop_back();
}
int stack::min()
{
return minValue.back();
}
3.求子数组的最大和(数组)
int maxSubarray(int *a,int n)
{
int f=0,g=0;
for(int i=0;i<n;++i)
{
g=max(g+a[i],a[i]);
f=max(f,g);
}
return f;
}
4.在二元树中找出和为某一值的所有路径(树)
struct Node
{
int val;
Node *left,*right;
Node(int x):val(x),left(NULL),right(NULL){}
};
void dfs(Node *root,int sum,vector<int> &path,int &s)
{
if(!root)return;
path.push_back(root->value);
s+=root->value;
if(!root->left&&!root->right&&s==sum)
{
for(int i=0;i<path.size();++i)cout<<path[i]<<' ';
cout<<endl;
}
dfs(root->left,sum,path,s);
dfs(root->right,sum,path,s);
s-=path.back();
path.pop_back();
}
void printPath(Node *root,int sum)
{
vector<int> path;
int s=0;
dfs(root,sum,path,s);
}
(5)查找最小的k个元素(数组)
(6)
(35)
int f(vector<vector<int> > vec)
{
int m=vec.size();
int n=vec[0].size();
int max=0,sum=0,x,y;
for(int i=0;i<=m-2;++i)
{
int colSum=vec[i][0]+vec[i+1][0];
for(int j=1;j<=n-1;++j)
{
sum=colSum;
colSum=vec[i][j]+vec[i+1][j];
sum+=colSum;
if(sum>max)
{
max=sum;
x=i;
y=j-1;
}
}
}
cout<<vec[x][y]<<' '<<vec[x][y+1]<<endl;
cout<<vec[x+1][y]<<' '<<vec[x+1][y+1]<<endl;
return max;
}