1.树-Minimum Depth of Binary Tree
求二叉树最小深度
注意是最小深度,不是最大
class Solution {
public:
int run(TreeNode *root) {
if(root==NULL)
return 0;
int ans=1;
queue<TreeNode*>q;
q.push(root);
while(!q.empty()){
int size=q.size();
while(size--){
TreeNode *a;
a=q.front();
q.pop();
if(a->left==NULL&&a->right==NULL) return ans;
if(a->left!=NULL) q.push(a->left);
if(a->right!=NULL) q.push(a->right);
}
ans++;
}
}
};
2.栈- evaluate-reverse-polish-notation
后缀数组
遇到数字,存进栈里,遇到符号,取出来两个数计算。
vector遍历,auto x:函数名。
string转化为字符串,s.c_str();
字符串转化为数字,atoi();
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int>s;
for(auto x:tokens){
if(x=="+"||x=="-"||x=="*"||x=="/")
{
int a=s.top();s.pop();
int b=s.top();s.pop();
if(x=="+")
s.push(a+b);
if(x=="-")
s.push(b-a);
if(x=="*")
s.push(a*b);
if(x=="/")
s.push(b/a);
}
else
s.push(atoi(x.c_str()));
}
int ans=s.top();s.pop();
return ans;
}
};
3.穷举- max-points-on-a-line
求一个平面内最多有多少点在一条线上
注意重合的点和斜率不存在的点。
map应该开在第一个for循环里
/**
* Definition for a point.
* struct Point {
* int x;
* int y;
* Point() : x(0), y(0) {}
* Point(int a, int b) : x(a), y(b) {}
* };
*/
class Solution {
public:
int maxPoints(vector<Point> &points) {
int n=points.size();
if(n<=2)
return n;
int ans=0;
for(int i=0;i<n;i++){
int d=1;//重合的点
map<double,int>m;
for(int j=i+1;j<n;j++){
if(points[i].x==points[j].x)
{
if(points[i].y==points[j].y)
d++;
else
m[INT_MAX]++;
}
else
{
double k=(points[i].y-points[j].y)*1.0/(points[i].x-points[j].x);
m[k]++;
}
}
ans=max(ans,d);
for(auto it=m.begin();it!=m.end();it++)
ans=max(ans,it->second+d);
}
return ans;
}
};