LeetCode - Container With Most Water
来源:互联网 发布:域名对应多个ip 编辑:程序博客网 时间:2024/04/29 04:34
题目描述:
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 linei 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.
假设当前最优解为(i, ai),(j, aj),那么可以初始化i=1,j=n,从坐标两端开始搜索,根据s=(j-i)*min(ai,aj),不断更新最优解,必定能找到最优解。
这是因为i和j的移动是由ai和aj来判断的,必须让高度较小的一方移动,当ai<aj时,ai与aj-1、aj-2、aj-3......的组合不必考虑,因为高度不变,长度减小。所以每次移动即相当于舍弃了(j-i-1)种组合,只需要考虑每次移动后的这一种组合是否为最优解即可。由i=1,j=n到i=j需要n-1次移动,依次舍弃不需要考虑的(n-2)、(n-3)、(n-4).....2、1种组合,真正可能存在最优解的只有(n-1)次移动产生的(n-1)种组合,所以总组合数为(n-1)+(n-2)+(n-3)+(n-4).....+2+1=C(n,2),这正是i和j所有可能的组合数。
可见此方法在保证不遗漏的情况下,只考虑了(n-1)种组合而舍弃了其余的不可能存在最优解的组合,大大降低了时间复杂度。
class Solution {public: int maxArea(vector<int>& height) {int i=0;int j=height.size()-1;int s=0;while(i<j){if(min(height[i],height[j])*(j-i)>s)s=min(height[i],height[j])*(j-i);if(height[i]<height[j]){i++;}else j--;}return s; }};
- LeetCode: Container With Most Water
- [LeetCode]Container With Most Water
- LeetCode Container With Most Water
- LeetCode: Container With Most Water
- [Leetcode] Container With Most Water
- Leetcode: Container With Most Water
- [LeetCode] Container With Most Water
- LeetCode Container With Most Water
- [Leetcode] Container With Most Water
- [LeetCode]Container With Most Water
- LeetCode-Container With Most Water
- Container With Most Water leetcode
- LeetCode - Container With Most Water
- LeetCode: Container With Most Water
- Leetcode: Container With Most Water
- 【LeetCode】Container With Most Water
- Leetcode: Container With Most Water
- LeetCode:Container With Most Water
- 常见系统调用总结
- 经典的c++面试题
- 谈一谈对JS闭包的理解
- 函数指针、指针函数类
- 103. Binary Tree Zigzag Level Order Traversal
- LeetCode - Container With Most Water
- poj1811(大质数判定与大数分解的模板题)
- Leetcode #9 Palindrome Number
- Ubuntu16.04 + cuda8.0 + GTX1080 + matlab14.04a + Opencv3.0 + caffe 安装教程
- Delphi中,让程序只运行一次的方法
- 面试总结
- 设计模式-类图和对象图
- 常用排序算法之归并排序
- X264中的sad-a.asm