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. html
Note: You may not slant the container. java
https://oj.leetcode.com/problems/container-with-most-water/ .net
思路1:O(n^2)复杂穷举全部的状况,too young too simple. 指针
思路2::两个指针i,j分别指向首位,选择两者中小的向中间移动,同时更新最大值。这个想法的基础是,若是i的长度小于j,若是移动j,短板在i,不可能找到比当前记录的area更大的值了,只能经过移动i来找到新的可能的更大面积。 code
public class Solution { public int maxArea(int[] height) { int n = height.length; int maxA = 0; int curA = 0; int i = 0, j = n - 1; while (i < j) { if (height[i] <= height[j]) { curA = Math.abs(j - i) * height[i]; if (curA > maxA) maxA = curA; i++; } else { curA = Math.abs(j - i) * height[j]; if (curA > maxA) maxA = curA; j--; } } return maxA; } public static void main(String[] args) { System.out.println(new Solution().maxArea(new int[] { 2, 2, 2 })); System.out.println(new Solution().maxArea(new int[] { 1, 2, 3 })); System.out.println(new Solution().maxArea(new int[] { 2, 3, 3 })); } }
参考: orm
http://blog.csdn.net/wzy_1988/article/details/17248209 htm
http://www.cnblogs.com/zhaolizhen/p/Containerwater.html blog