剑指offer_2020_9_19

剑指 Offer 55 - I. 二叉树的深度

class Solution {
public:
    int maxDepth(TreeNode* root) {
    if(root==NULL) return 0;
    else return max(maxDepth(root->left)+1,maxDepth(root->right)+1);
    }
};

剑指 Offer 55 - II. 平衡二叉树

class Solution {
public:
    bool isBalanced(TreeNode* root) {
    if(root==NULL) return true;
    else if((maxdepth(root->left)-maxdepth(root->right)>1)||(maxdepth(root->right)-maxdepth(root->left)>1))
    return false;
    return isBalanced(root->left)&&isBalanced(root->right);
    }

    int maxdepth(TreeNode*root)
    {
        if(root==NULL) return 0;
        else return max(maxdepth(root->left)+1,maxdepth(root->right)+1);
    }
};

剑指 Offer 56 - I. 数组中数字出现的次数(异或)

class Solution {
public:
    vector<int> singleNumbers(vector<int>& nums) {
    int l=nums.size();
    if(l<2) return nums;
    vector<int>res(2);
    int tmp=nums[0];
    for(int i=1;i<l;i++)
    {
        tmp^=nums[i];
    }
    int id=0;
    for(int i=0;i<32;i++)
    {
        if((tmp>>i&1)==1)
         {id=i;
         break;}
    }
    for(int i=0;i<l;i++)
    {
        if((nums[i]>>id&1)==1)
        res[0]^=nums[i];
        else
        res[1]^=nums[i];
    }
    return res;
    }
};

剑指 Offer 56 - II. 数组中数字出现的次数 II

class Solution {
public:
    int singleNumber(vector<int>& nums) {
    map<int,int>m;
    for(int i=0;i<nums.size();i++)
    {
        m[nums[i]]++;
    }
    for(auto it=m.begin();it!=m.end();it++)
    {
        if(it->second==1)
        return it->first;
    }
    return 0;
    }
};

剑指 Offer 57. 和为s的两个数字

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
    if(nums.empty()) return {};
    int left=0,right=nums.size()-1;
    while(left<right)
    {
        if(nums[left]+nums[right]==target) return{nums[left],nums[right]};
        else if(nums[left]+nums[right]<target) left++;
        else if(nums[left]+nums[right]>target)right--;
    }
    return {};
    }
};

剑指 Offer 57 - II. 和为s的连续正数序列

class Solution {
public:
    vector<vector<int>> findContinuousSequence(int target) {
    vector<int>tmp1;
    vector<vector<int>>res;
    int n=(target>>1)+1;
    int left=1,right=1;
    int tmp=left;
    while(left<n)
    {
        if(tmp<target)
        {
            right++;
            tmp+=right;
        }
        else if(tmp>target)
        {
            tmp-=left;
            left++;
        }
        else
        {
            for(int i=left;i<=right;i++)
            {tmp1.push_back(i);
            }
            res.push_back(tmp1);
            tmp1.clear();
            right++;
            tmp+=right;
        }
    }
    return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值