第一周算法设计与分析:Container with most water
2017-02-25 16:40
211 查看
题目来自此处
描述如下:
Given n non-negative integers a1, a2, ...,
an, where each represents a point at coordinate (i,
ai). n vertical lines are drawn such that the two endpoints of line
i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
O(n^2)算法:
一开始是想从前往后扫描,一条边不断与右边剩余的所有边匹配。但是这种算法在数据较多的情况下超时。
所以还是放弃这种懒惰做法
O(n)算法:
这个其实是一个求面积最大化的问题。考虑一个初始值——使x轴上的边最大化作为宽度,高度是min(a1,an)。
然后,作为高度的两条边,不断往中心推进,直到左端大于右端,则停止迭代。其中比较关键的地方在于,在迭代过程中左端高度与右端高度的比较,如果左端的高度小于右端的高度,表明左端的高度是作为整体面积的高度,那么他跟右端之间所有边组成的容器都以他为高度(然而可能还有更矮的),这些可能的组合不可能比目前组合的面积大。所以舍弃左端与这些边的组合,即左端往右移。反之如果左端的高度大于右端的,那么右端往左移。
关键的代码如下:
int maxArea(vector<int> height)
{
int cur_i = 0;
int cur_j = height.size()-1;
int water_max = (height.size()-1)*min(height[i],height[j]);
while(cur_i<cur_j)
{
water_max = max(water_max,min(height[cur_i],height[cur_j])*(cur_j-cur_i));
if(height[cur_i]<height[cur_j])
cur_i++;
else
cur_j--;
}
cout<<water_max<<endl;
return water_max;
}
height包含所有边。
大概就这样咯~想个算法真的可以想到头皮发麻~
描述如下:
Given n non-negative integers a1, a2, ...,
an, where each represents a point at coordinate (i,
ai). n vertical lines are drawn such that the two endpoints of line
i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
O(n^2)算法:
一开始是想从前往后扫描,一条边不断与右边剩余的所有边匹配。但是这种算法在数据较多的情况下超时。
所以还是放弃这种懒惰做法
O(n)算法:
这个其实是一个求面积最大化的问题。考虑一个初始值——使x轴上的边最大化作为宽度,高度是min(a1,an)。
然后,作为高度的两条边,不断往中心推进,直到左端大于右端,则停止迭代。其中比较关键的地方在于,在迭代过程中左端高度与右端高度的比较,如果左端的高度小于右端的高度,表明左端的高度是作为整体面积的高度,那么他跟右端之间所有边组成的容器都以他为高度(然而可能还有更矮的),这些可能的组合不可能比目前组合的面积大。所以舍弃左端与这些边的组合,即左端往右移。反之如果左端的高度大于右端的,那么右端往左移。
关键的代码如下:
int maxArea(vector<int> height)
{
int cur_i = 0;
int cur_j = height.size()-1;
int water_max = (height.size()-1)*min(height[i],height[j]);
while(cur_i<cur_j)
{
water_max = max(water_max,min(height[cur_i],height[cur_j])*(cur_j-cur_i));
if(height[cur_i]<height[cur_j])
cur_i++;
else
cur_j--;
}
cout<<water_max<<endl;
return water_max;
}
height包含所有边。
大概就这样咯~想个算法真的可以想到头皮发麻~
相关文章推荐
- 第一周作业:11 container with most water
- Leetcode: Container With Most Water
- 11. Container With Most Water
- #383 Container With Most Water
- [11]Container With Most Water
- Container With Most Water
- 4.20 leetcode -20 container-with-most-water
- [LeetCode] Container With Most Water
- 11. Container With Most Water
- LeetCode-11-Container-With-Most-Water 贪心
- Container With Most Water
- container-with-most-water
- Container With Most Water
- 11. Container With Most Water
- 【LeetCode算法练习(C++)】Container With Most Water
- 算法分析与设计——LeetCode Problem.11 Container With Most Water
- Container With Most Water
- 开始刷leetcode day17:Container With Most Water
- <leetcode>Container With Most Water
- Container With Most Water