剑指offer_2020_9_22

剑指 Offer 66. 构建乘积数组

class Solution {
public:
    vector<int> constructArr(vector<int>& a) {
    
    int l=a.size();
    vector<int>res(l);
    for(int i=0,cur=1;i<l;i++)
    {
        res[i]=cur;
        cur*=a[i];
    }
    //res[i]为i左边数的乘积
    //下面乘右边的数
    for(int i=l-1,cur=1;i>=0;i--)
    {
        res[i]*=cur;
        cur*=a[i];
    }
    return res;

    }
};

剑指 Offer 67. 把字符串转换成整数

class Solution {
public:
    int strToInt(string str) {
    int i=0;
    bool neg=false;
    while(i<str.size()&&str[i]==' ')i++;
    if(!isdigit(str[i])&&str[i]!='+'&&str[i]!='-')
    return 0;
    if(str[i]=='-')
    {
       neg=true;
       i++;
    }
    else if(str[i]=='+') i++;
    long res=0;
    while(isdigit(str[i]))
    {
        //数字
        res=res*10+str[i]-'0';
        if(neg==false&&res>INT_MAX)
        return INT_MAX;
        else if(neg==true&&-res<INT_MIN)
        return INT_MIN;
        i++;
    }
    return neg==true?-res:res;
    }
};

剑指 Offer 68 - I. 二叉搜索树的最近公共祖先

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
    if(root==NULL)return root;
    if(root->val>p->val&&root->val>q->val)
    return lowestCommonAncestor(root->left,p,q);
    if(root->val<p->val&&root->val<q->val)
    return lowestCommonAncestor(root->right,p,q);
    return root;
    }
};

剑指 Offer 68 - II. 二叉树的最近公共祖先

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
    if(root==NULL) return root;
    if(root==q||root==p) return root;
    TreeNode*left=lowestCommonAncestor(root->left,p,q);
    TreeNode*right=lowestCommonAncestor(root->right,p,q);
    //p,q一左一右
    if(left!=NULL&&right!=NULL)
    return root;
    //都在左边
    if(left!=NULL)
    return left;
    //都在右边
    if(right!=NULL)
    return right;
    return NULL;
    }
};
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试 返回首页