LeetCode: Container With Most Water
11. Container 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.
暴力解法:遍历所有可能的情况,计算面积,返回最大值,时间复杂度为O(n^2)。很不幸,该方法目前看答案是对的,但是leetcode中提交显示超时。。。
class Solution { public: int maxArea(vector<int>& height) { int maxarea = 0; for (int i = 0; i < height.capacity(); i++) { for (int j = 1; j <= height.capacity() - i-1; j++) { int hei = height[i] > height[i+j] ? height[i+j]:height[i]; if (maxarea < hei*j) maxarea = hei*j; } } return maxarea; } };
容器面积为h[i]和h[j]中较短的边长乘以i和j间的距离,所以最终的h[maxi]和h[maxj]的左右没有比其自身更高的边。所以我们从两头向中间靠拢,先从较短的边进行靠拢,找到比其更高的边再进行判断。
class Solution { public: int maxArea(vector<int>& height) { int maxarea = 0; int i = 0, j = height.size() - 1; while (i<j) { int hei = height[i] > height[j] ? height[ j] : height[i]; if (maxarea < hei*abs(i - j)) { maxarea = hei*abs(i - j); } if (height[i] < height[j]) { int k = i; while (height[k]<=height[i]&&k<j) { k++; } i = k; } else { int h = j; while (height[h] <= height[j] && i<h) { h--; } j = h; } } return maxarea; } };
附:vector中size和capacity,"[]"和at()的区别,
size指目前容器中实际有多少元素,对应的resize(size_type)会在容器尾添加或删除一些元素,来调整容器中实际的内容,使容器达到指定的大小。capacity指最少要多少元素才会使其容量重新分配,对应reserve(size_type new_size)会这置这个capacity值,使它不小于所指定的new_size。
at()提供了越界检查的功能,使用起来更安全,同时比起operator[]来代价也更大。
参考链接:http://blog.163.com/jxguo_05/blog/static/719401002010102523831645/
http://blog.csdn.net/a83610312/article/details/8548519