leetCode练习(11)

题目:Container With Most Water

难度: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.

中文翻译:给出一个数组a[n],其中a[I]=x,表示坐标为(I,x)的点。任意两个点I,j的面积s=(Abs(I-j))*MIN(a[I],a[j]),求其中面积s最大的可取值。

解题思路:最开始使用二重循环,穷举所有可能,暴力求解。结果提交之后显示超时=。= 于是开始寻求更好的算法。

由于是两点问题,下标又是从0到length,自然想到由I=0,j=length-1,由外向内夹逼。基本逻辑是:

if: height[I]原值

对于j 同理。

计算每次移动后的面积s并与max比较,若s更大,则更新max。

具体代码如下:

public class Solution {
    public int maxArea(int[] height) {
       if(height==null||height.length<2){
			return 0;
		}
		
		int temp;
		int res=0;
		int len=height.length;
		int i=0,j=len-1;
		
		while(iheight[j])?height[j]:height[i]);
			res=res>temp?res:temp;
			
			if(height[i]<=height[j]){
//				System.out.println("height["+i+"]更小");
				temp=height[i];
				while(height[i]<=temp&&iheight[j]){
//				System.out.println("height["+j+"]更小");
				temp=height[j];
				while(height[j]<=temp&&j>i){
					j--;
//					System.out.println("j="+j);
				}
				continue;
			}
		}
		return res;
    }
}

你可能感兴趣的:(leetCode)