刷题第二天
1、两数之和
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
class Solution{
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
unordered_map<int, int> map;
for(int i = 0; i < nums.size(); i++){
int tmp = target - nums[i];
if(map.find(tmp) != map.end()){
res.push_back(map[tmp]);
res.push_back(i);
break;
}
map[nums[i]] = i;
}
return res;
}
};
2、二叉树的我最近公共祖先
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
class Solution{
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr) return nullptr;
if(root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if(left == nullptr) return right;
if(right == nullptr) return left;
if(left && right) return root;
return nullptr;
}
};
3、二叉树的右视图
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
class Solution{
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> res;
if(root == nullptr) return res;
queue<TreeNode*> queue;
queue.push(root);
while(!queue.empty()){
int n = queue.size();
for(int i = 0; i < n; i++){
TreeNode* node = queue.front();
queue.pop();
if(node->left) queue.push(node->left);
if(node->right) queue.push(node->right);
if(i == n - 1) res.push_back(node->val);
}
}
return res;
}
};
4、二分查找
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
class Solution{
public:
int search(vector<int>& nums, int target) {
int mid = 0, left = 0, right = nums.size() - 1;
while(left <= right){
mid = left + (right - left) / 2;
if(nums[mid] == target) return mid;
if(nums[mid] > target) right = mid - 1;
else left = mid + 1;
}
return -1;
}
};