leetcode刷题日记

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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值