剑指 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;
}
};