腾讯精选50题—Day4题目16,20,21
打卡的第四天,冲鸭~~~
目录
1. 题目16
(1)题目描述
(2)思路
双指针法~
(3)题解
有个陷阱!result的初始化为INT_MAX会报错......这个时候我们只需要初始化为INT_MAX/2就好啦。
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int len = nums.size();
int result = INT_MAX/2;
sort(nums.begin(), nums.end());
if (len < 3)
return 0;
for (int i = 0; i < len; i++)
{
int low = i + 1;
int high = len - 1;
while (low < high)
{
int temp_sum = nums[i] + nums[low] + nums[high];
int new_diff = abs(temp_sum - target);
int old_diff = abs(result - target);
if (new_diff < old_diff)
result = temp_sum;
if (temp_sum > target)
{
high--;
}
else if(temp_sum < target){
low++;
}
else {
return target;
}
}
}
return result;
}
};
结果:
时间复杂度: (包含排序和两层循环,简写为)
空间复杂度: (包含排序所需和存储的数组,简写为)
2. 题目20 括号匹配问题
(1)题目描述
(2)思路
经典的数据结构问题,使用辅助栈,解决,提供两种解法,第一种是经典的使用栈的做法,第二种是栈+map的优化。
(3)题解
a. 辅助栈——经典做法(为啥我代码这么多...哦原来人家都用了map....)
遇到')',']'以及'}'就出栈判断其与栈顶元素是否匹配,其他情况都进栈(由于题目说只有6种字符),如果不匹配或者遍历过一遍字符串但栈不为空,说明字符串不匹配返回false。
class Solution {
public:
bool isValid(string s) {
stack<char> q_stack;
bool result = false;
int len = s.size();
if (len == 0)
{
return true;
}
else {
q_stack.push(s[0]);
}
for (int i=1; i<len; i++)
{
switch (s[i])
{
case ')':
{
if (q_stack.empty())
return false;
char ch = q_stack.top();
if (ch == '(')
{
q_stack.pop();
}
else {
return false;
}
continue;
}
case ']':
{
if (q_stack.empty())
return false;
char ch = q_stack.top();
if (ch == '[')
{
q_stack.pop();
}
else {
return false;
}
continue;
}
case '}':
{
if (q_stack.empty())
return false;
char ch = q_stack.top();
if (ch == '{')
{
q_stack.pop();
}
else {
return false;
}
continue;
}
default:
{
q_stack.push(s[i]);
continue;
}
}
}
if (!q_stack.empty())
return false;
else
return true;
}
};
时间复杂度:
空间复杂度:
结果:
b. 使用map优化a
class Solution {
public:
bool isValid(string s) {
unordered_map<char, char> map = {
{')', '('},
{']', '['},
{'}', '{'}
};
stack<char> sta;
for (char ch : s)
{
if (map.count(ch))
{
if (sta.empty() || sta.top() != map[ch])
return false;
sta.pop();
}
else {
sta.push(ch);
}
}
return sta.empty();
}
};
结果:
时间复杂度:
空间复杂度: map的空间复杂度为常数,略去。
3. 题目21 合并两个有序链表
(1)题目描述
(2)思路
递归,递归,递归!!!递归真的非常巧妙~
(3)题解
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == NULL)
return l2;
if (l2 == NULL)
return l1;
if (l1->val < l2->val)
{
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}
else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};
结果:
时间复杂度:
空间复杂度: ,递归消耗栈空间(栈空间的大小取决于递归的深度)