11 contain with most water
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.
题目的意思即为给定一组点,使其容积最大。
画个图示意一下
每个非负整数类似于“水缸”的一条边,an的值即为边的高度,每两条边与x轴组成一个“水缸”,要求出“水缸”能最多容纳多少水。
最简单的方法便是两两组成一个“水缸”,把每种可能性都算一次,进行比较,就能得出最多能容纳多少水。
利用二重循环和比较来求得最大值,时间复杂度是
O(n2)
O
(
n
2
)
参考代码如下:
class Solution {
public:
int maxArea(vector<int>& height) {
int max = 0;
for(int i = 0; i < height.size(); i++) {
for(int j = i + 1; j < height.size(); j++) {
int calHeight = height[i];
if(height[j] < height[h])
calHeight = height[j];
int tempArea = calHeight * (j - i);
if(tempArea > max)
max = tempArea;
}
}
return max;
}
};
当然这是过不了检测的
O(n2) O ( n 2 ) 的时间复杂度会使得当n很大的时候要花费相当多的时间来求解问题,效率并不高。
根据木桶原理,一只木桶能盛多少水,并不取决于最长的那块木板,而是取决于最短的那块木板。这道题也是符合这个原理,“水缸”能装多少水,两条边短的那一根的高度是一个很大的影响(决定了实际计算高度),同时“水缸”的宽度也会影响到能装的水量。假设我们从两端同时开始选中,先取最左和最右的两根“木板”的情况,同时,在任意其他情况下,“水缸”的宽一定比这种情况小。为了使得容量增加,只能移动“木板”搜寻其他情况,根据木桶原理,我们应当使得短的一边变高,即为,假设左边的木板比右边矮的时候,我们应该改变左边的木板,往右搜寻是否有比目前最大容量还大的情况,而右边高的木板则保留。当短的木板被“遗弃”,选择往后搜索时,必然有很多种情况被排除。假如a0,a1,……,an,当前情况为{a0, an},若a0 < an,此时a0→a1来寻找新的可能性,而被排除的{a0,a1},……,{a0,an-1},“水缸”的宽度一定小于{a0,an},而且高度被a0限制(a0为上界),所以可以确定这些被排除的情况的水容量一定比{a0,an}小。所以我们只需要搜索一遍,以 O(n) O ( n ) 的时间复杂度便能得到结果。
参考代码如下:
class Solution {
public:
int maxArea(vector<int>& height) {
int max = 0;
int left = 0, right = height.size() - 1;
while(left < right) {
int calHeight = height[left];
if(height[right] < height[left])
calHeight = height[right];
int contain = calHeight * (right - left);
if(contain > max)
max = contain;
if(height[left] < height[right])
left++;
else
right--;
}
return max;
}
};