时间限制:1秒
空间限制:32768K
热度指数:69012
算法知识视频讲解
题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
if(!pRoot) return 0;
return max(TreeDepth(pRoot->left)+1,TreeDepth(pRoot->right)+1);
}
};
时间限制:1秒
空间限制:32768K
热度指数:212992
算法知识视频讲解
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
int row = matrix.size();
int col = matrix[0].size();
int left=0,right=col-1,top=0,btm=row-1;
vector<int> res;
while(left<=right&&top<=btm)
{
for(int i=left;i<=right;i++)
res.push_back(matrix[top][i]);
for(int i=top+1;i<=btm;i++)
res.push_back(matrix[i][right]);
if(top!=btm)
{
for(int i=right-1;i>=left;i--)
res.push_back(matrix[btm][i]);
}
if(left!=right)
{
for(int i=btm-1;i>=top+1;i--)
res.push_back(matrix[i][left]);
}
left++,right--,top++,btm--;
}
return res;
}
};
时间限制:1秒
空间限制:32768K
热度指数:126845
算法知识视频讲解
题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
void push(int value) {
st.push(value);
if(smin.empty()) smin.push(value);
else if(smin.top()>value) smin.push(value);
}
void pop() {
if(smin.top()==st.top())
smin.pop();
st.pop();
}
int top() {
return st.top();
}
int min() {
return smin.top();
}
private:
stack<int> st;
stack<int> smin;
};
时间限制:1秒
空间限制:32768K
热度指数:152304
算法知识视频讲解
题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
class Solution {
public:
bool IsPopOrder(vector<int> pushV,vector<int> popV) {
int len1=pushV.size(),len2=popV.size();
if(len1!=len2) return false;
stack<int>st;
int now=0;
for(int i=0;i<len1;i++)
{
st.push(pushV[i]);
while(!st.empty()&&st.top()==popV[now])
{
now++;
st.pop();
}
}
if(now==len2) return true;
else return false;
}
};