LeetCode 11 Container With Most Water
2015-07-28 21:06
375 查看
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.
解法思路:题目大意是以x轴 ,两个以顶点在(i, ai)、(j,
aj)到x轴的垂直直线所围成的凹槽的面积的最大值。
暴力法,O(n^2) 的复杂度,两层循环遍历所有节点,找到最大值。但是明显超时了,因此,需要改进。
在这里设置两个指针,分别从最左边和最右边遍历。然后进行判断,若出现左边低于右边高度时,将左边指针加1.若出现左边高于右边的时候,则右边加1.这里这样做的原因是,当出现较低的高度的时候,替换这个低的高度,从而遍历寻找高的高度来提高面积。如果以相反的做法,则不能提高面积。
暴力法代码如下:
int maxArea1(int* height, int heightSize){ int max = 0; for (int i = 0; i < heightSize; i++){ int t = heightSize - 1; while (t>=i) { int h = height[i]>height[t] ? height[t] : height[i]; int temp = (t-i)*h; if (temp >= max){ max = temp; } t--; } } return max; }
双指针代码如下:复杂度O(n)
int maxArea(int *height, int heightSize){ int max = 0; int left = 0; int right = heightSize-1; while (left < right){ int h = height[left]>height[right] ? height[right] : height[left]; int temp = (right - left)*h; if (temp >= max){ max = temp; } if (height[left] > height[right]){ right--; } else{ left++; } } return max; }
相关文章推荐
- hdu 5319 Painter(15多校第三场1004)
- hdu 5319 Painter(水)
- Contains Duplicate
- Hdu 2015 Multi-University Training Contest3
- tinyxml 使用说明http://blog.csdn.net/zww0815/article/details/8083550
- leetcode之路011 Container With Most Water
- 2015 Multi-University Training Contest 3 hdu 5316 Magician
- HDU5319.Painter
- FirstChildElement() http://baike.baidu.com/link?url=VdlvQlGU-NGLshFepuft_u3MRdjZ9CAfGhOYuL915Oo-9pb
- hdu 5319 Painter
- 7.28多校1004——模拟——Painter
- HDU 5319 Painter(2015多校联合)
- 2015 Multi-University Training Contest 3
- atcoder它A Mountaineer
- HDU 5319 Painter
- hdu 5316 Magician(2015 Multi-University Training Contest 3)
- ZOJ 3802 Easy 2048 Again 像缩进DP
- HDU 5319 Painter (模拟)
- hdu5326_(优美的并查集解法)2015 Multi-University Training Contest 3(1011)
- XSSFDataValidationHelper.createDateConstraint有Bug