Leetcode -- Container With Most Water
2015-08-11 15:23
513 查看
题目:
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.
分析:若干条线,找两条线使得其与X轴围成的面积最大。
如果是暴力的穷搜,肯定可以得到答案,但复杂度达到O(N^2),耗时,leetcode里面是过不去的。
思路:从数据集的两头同时开始。当ai小于aj时,i ++; 反之,j–。直到二者相遇。理由,影响面积的是比较短的线,因此,每次只要改变比较短的线就好了。这个想法的复杂度是O(N)
代码:
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.
分析:若干条线,找两条线使得其与X轴围成的面积最大。
如果是暴力的穷搜,肯定可以得到答案,但复杂度达到O(N^2),耗时,leetcode里面是过不去的。
思路:从数据集的两头同时开始。当ai小于aj时,i ++; 反之,j–。直到二者相遇。理由,影响面积的是比较短的线,因此,每次只要改变比较短的线就好了。这个想法的复杂度是O(N)
代码:
int maxArea(vector<int>& height) { int len = height.size(); int max_area = 0, area = 0; int i = 0, j = len - 1; while(i < j) { if(height[i] < height[j]) { area = (j -i) * height[i]; i ++; } else { area = (j - i) * height[j]; j --; } if (area > max_area) { max_area = area; } } return max_area; }
相关文章推荐
- C++ Vector用法详解
- 大家注意vector, list, set, map成员函数erase
- java中vector与hashtable操作实例分享
- C++ vector删除符合条件的元素示例分享
- C++ Vector用法深入剖析
- vector与map的erase()函数详细解析
- vector,map,list,queue的区别详细解析
- C++ vector的用法小结
- stl容器set,map,vector之erase用法与返回值详细解析
- C++中vector的用法实例解析
- c++ vector(向量)使用方法详解(顺序访问vector的多种方式)
- 关于STL中vector容器的一些总结
- JAVA Vector源码解析和示例代码
- Java中的Vector和ArrayList区别及比较
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- Java中Vector和ArrayList的区别
- Vector 还是ArrayList