11. Container With Most Water题解
来源:互联网 发布:数据存储技术 编辑:程序博客网 时间:2024/05/29 20:05
- Total Accepted: 132924
- Total Submissions: 365451
- Difficulty: Medium
- Contributor: LeetCode
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.
1.题目意思:
给你一个顶点数组,例如{4,7,9},这个定点数组代表直角坐标系上三个点,(1,4),(2,7),(3,9),然后过这三个点,分别作垂直于X轴的线段,例如对于(1,4),线段的两个端点为(1,4)和(1,0),然后,我们可以得到三条垂直于X轴的线段。从这些线段中找出一对组合,使得,这对组合的 横坐标之差 乘以 两条线段中较短者的长度 的乘积最大。
2.
解题思路:
最大盛水量取决于两边中较短的那条边,而且如果将较短的边换为更短边的话,盛水量只会变少。所以我们可以用两个头尾指针,计算出当前最大的盛水量后,将较短的边向中间移,因为我们想看看能不能把较短的边换长一点。这样一直计算到左边大于右边为止就行了。先拿最左边的线段和最右边的线段作为组合,计算出乘积,然后,找两者中较为短的一方,慢慢向中间靠拢。举个例子,{4,3,7,2,9,7},先计算4和7的组合的乘积,然后找两者中比较小的一方,这里是4,让它向中间靠拢,向前走一步是3,但3比4小,所以计算3和7的组合是没有意义的,所以,继续向中间靠拢,发现了7,7比4大,所以有可能会得到比原来更大的面积,因此计算7和7的组合的乘积。重复这个过程,直至左边的工作指针大于等于右边的工作指针。
源代码:
public class Solution {
public int maxArea(int[] height) {
int maxArea = 0, left = 0;
int right = height.length - 1;
while (left < right) {
maxArea = Math.max(maxArea, Math.min(height[left], height[right]) * (right - left));//求两点之间的面积
if (height[left] < height[right]) {
left ++;
} else {
right--;
}
}
return maxArea;
}
}
- LeetCodet题解--11. Container With Most Water
- Leetcode题解:11. Container With Most Water
- leetcode题解-11. Container With Most Water
- 11. Container With Most Water LeetCode题解
- 11. Container With Most Water题解
- Leetcode题解-11. Container With Most Water
- leetcode题解Java | 11. Container With Most Water
- [模拟]LeetCode 11. Container With Most Water 题解
- 【LeetCode】【Python题解】Container with most water
- leetcode题解||Container With Most Water问题
- LeetCode题解:Container With Most Water
- LeetCode题解-11-Container With Most Water
- 011_LeetCode_11 Container With Most Water 题解
- 11.Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- Jquery使用AJAX请求跨域解决方法
- bzoj 4917: Hash Killer IV 模拟
- C++入门基础知识
- VB.net
- 53. Maximum Subarray
- 11. Container With Most Water题解
- Linux网络端口
- 查验身份证
- JAVA 8函数式编程(一):高阶函数
- 写测试类时没有@Test注解
- c#——三层登陆
- 一个整型数组里除了两个数字之外,其他的数字都出现了两次
- 50个必备的实用jQuery代码段+ 可以直接拿来用的15个jQuery代码片段
- LintCode(两数组的交)