您的位置:首页 > 大数据 > 人工智能

[LeetCode] Container With Most Water 简要分析

2015-12-04 16:42 483 查看

前言

这题非要说贪心的话也算是吧,不过最主要的特征还是双指针。LC的题好像不少都是扔倆头尾指针然后遍历一遍完事儿的。这道题倒是“短板效应”的不错体现了。

题目

题目链接

Givennnon-negativeintegersa1,a2,…,an,whereeachrepresentsapointatcoordinate(i,ai).nverticallinesaredrawnsuchthatthetwoendpointsoflineiisat(i,ai)and(i,0).Findtwolines,whichtogetherwithx-axisformsacontainer,suchthatthecontainercontainsthemostwater.

Note:Youmaynotslantthecontainer.

思路



图片看不清楚的话可右键复制链接转到图床再看。

代码

classSolution{
public:
intmaxArea(vector<int>&height){
intfirst=0;
intend=height.size()-1;
intresult=INT_MIN;
while(first<end)
{
intwidth=end-first;
intboard=height[end]<height[first]?height[end]:height[first];
intarea=board*width;
result=result>area?result:area;
if(height[first]<=height[end])
first++;
else
end--;
}
returnresult;
}
};



其他

JAVA果然过得比CPP快,Python和C#依旧垫底。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: