leetcode习题解答:11. Container With Most Water
来源:互联网 发布:爱普生tx800清零软件 编辑:程序博客网 时间:2024/06/02 19:39
难度:Medium
链接
描述:
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),耗时感人。下面有一个稍微改进的,二层循环从数组尾端向前扫描,可以排除一些情况,加快速度。
class Solution {public: int maxArea(vector<int>& height) { int max = 0; for(int i = 0; i < height.size(); i++){ int h = 0; for (int k = height.size()-1; k >= i+1; k--){ if (height[k] > height[i]){ int m = height[i]*(k-i); if (m > max)max = m; break; } else if (height[k] > h){ int h = height[k]; int m = h*(k-i); if (m > max)max = m; } } } return max; }};
但是这肯定不是最好的算法,可以有这么一种思路,从数组两端向中间逼近,但是要怎样设置条件呢?
我们知道计算面积,height取的是两边的最小值,那么如果出现一边比较高的时候比如height[left] > height[right],left可以不改动,而right--来寻找一个更高的height,如果right
比较高,那么left++去寻找一个更高的height,这样不断计算面积,最后就能得出最大面积。
class Solution {public: int maxArea(vector<int>& height) { int left = 0; int right = height.size()-1; int max = 0; while(left < right){ int minHeight = height[left]<height[right]?height[left]:height[right]; int newMax = (right-left)*minHeight; if (newMax > max) max = newMax; if (height[left] < height[right]) left++; else right--; } return max; }};
阅读全文
0 0
- leetcode习题解答:11. Container With Most Water
- LeetCode 11. Container With Most Water
- [LeetCode]11.Container With Most Water
- LeetCode --- 11. Container With Most Water
- LeetCode 11.Container With Most Water
- [Leetcode] 11. Container With Most Water
- [leetcode] 11.Container With Most Water
- 【leetcode】11. Container With Most Water
- [LeetCode]11. Container With Most Water
- 11. Container With Most Water LeetCode
- leetcode 11. Container With Most Water
- leetcode 11.Container With Most Water
- [LeetCode OJ]11. Container With Most Water
- [leetcode] 11. Container With Most Water
- Leetcode 11. Container With Most Water
- leetcode 11.Container With Most Water
- leetcode 11. Container With Most Water
- LeetCode 11. Container With Most Water
- 分享下多年积累的对JAVA程序员成长之路的总结
- viewpager切换
- Android之十三图片的2D翻转
- js数组的常用方法
- C# 3DES 加密
- leetcode习题解答:11. Container With Most Water
- ssm框架搭建(主要配置步骤)
- 网站开发流程,个人心得,欢迎补充
- 【NOIP2017提高A组集训10.25】摘Galo (树形dp)
- Spring Boot系列02-Spring Boot + JSP 整合进行网页开发
- 初识网站安全
- flask-web开发-用户认证代码分析(四)
- 反射
- 互联网协议入门(一)