Datawhale-leetcode第三天打卡(leetcode保姆级教程)——题号011,014,015
今天是打卡的第三天,我们废话少说,直接看题。
第一题11. 盛最多水的容器
题目描述:
给你 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器。
图意提示:
这个题目呢,主要是用了双指针的解题方法。
为什么能用双指针不会错过最优解呢,请看证明
https://leetcode-cn.com/problems/container-with-most-water/solution/zhi-guan-de-shuang-zhi-zhen-fa-jie-shi-by-na-kong/
完整代码
class Solution {
public:
int maxArea(vector<int>& height) {
int lf=0,rf=height.size()-1;
cout<<lf<<endl;
cout<<rf<<endl;
for(int i=0;i<height.size();i++)
{
cout<<height[i]<<endl;
}
int max=-1;
if(rf-lf==1)
{
max=min(height[lf],height[rf]);
}
while(rf>lf)
{
cout<<max<<"这里是max"<<endl;
if(max<min(height[lf],height[rf])*(rf-lf))
max=min(height[lf],height[rf])*(rf-lf);
if(height[lf]<height[rf])
{
lf++;
}
else
{
rf--;
}
}
return max;
}
};
记得在leetcode里运行。
第二题14. 最长公共前缀
这个简单的匹配题,我们在这里先看看题。
题目描述:
代码如下
class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
int len=strs.size();
string a="";
int min=INT_MAX;
if(len==0||strs.empty())
{
return "";
}
for (int i=0;i<len;i++)
{
if(min>strs[i].size())
{
min=strs[i].size();
}
}
cout<<strs[0].size()<<endl;
for(int i=0;i<min;i++)
{
for(int j=1;j<len;j++)
{
if(i==min||strs[0][i]!=strs[j][i])
return a;
}
a=a+strs[0][i];
}
return a;
}
};
第三题15. 三数之和
这个我不会,菜鸡哭泣,调半天没有调好,总是有问题出现。
有兴趣的大佬可以自己不看题解做做
今天打卡晚的原因
题目描述:
直接上代码
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
int n = nums.size();
sort(nums.begin(), nums.end());
vector<vector<int>> ans;
// 枚举 a
for (int first = 0; first < n; ++first) {
// 需要和上一次枚举的数不相同
if (first > 0 && nums[first] == nums[first - 1]) {
continue;
}
// c 对应的指针初始指向数组的最右端
int third = n - 1;
int target = -nums[first];
// 枚举 b
for (int second = first + 1; second < n; ++second) {
// 需要和上一次枚举的数不相同
if (second > first + 1 && nums[second] == nums[second - 1]) {
continue;
}
// 需要保证 b 的指针在 c 的指针的左侧
while (second < third && nums[second] + nums[third] > target) {
--third;
}
// 如果指针重合,随着 b 后续的增加
// 就不会有满足 a+b+c=0 并且 b<c 的 c 了,可以退出循环
if (second == third) {
break;
}
if (nums[second] + nums[third] == target) {
ans.push_back({nums[first], nums[second], nums[third]});
}
}
}
return ans;
}
};
解决任务!(想念世界上最可爱的CC)