HF_Cherish

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1. Question

 给n个非负整数,在二维坐标系中,将(i,ai)与(i,0)连线,得到n条线。从n条线中找两条,与x轴构成一个非密封容器(容器不能倾斜),使得该容器盛水量最多。

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.

 

2. Solution

2.1 O(n2)

遍历所有的线组合,计算得到最大的。

 

2.2 O(n)

采用双指针。实际面积是min(ai, aj)*(j-i)

  • pi = 0;
  • pj = len-1;
  • 计算点ai和点aj所在的线构成的面积,并与max_area比较。
    • 如果ai <= aj, i++ (此时,ai是实际面积计算中的高,而此时的宽已是最大,从而以ai为高的最大面积已经计算得到,无需再考虑以ai为高的区域。此外,在一次次指针行走后,总能保证当前的某个指针所指的点高度比排除掉的任意点要高,从而即使后来遇到比之前排除掉的更低的点,也依然可以得到以该更低点为高的最大面积,因此无需再考虑以ai为梯形中的较高边的情况。总而言之,此时ai所在线无需再考虑)
    • 如果aj > ai, j--
import java.util.Map.Entry;

public class Solution {
    public int maxArea( int[] height ){
        int left = 0;
        int right = height.length - 1;
        int maxArea = 0;
        while( left < right ){
            int nowH;
            if( height[left] < height[right] )
                nowH = height[left++];
            else
                nowH = height[right--];
            maxArea = Math.max( maxArea, (right-left+1) * nowH );
        }
        return maxArea;
    }
}
View Code

 

        

 

posted on 2015-06-23 21:51  HF_Cherish  阅读(197)  评论(0编辑  收藏  举报