LeetCode Solutions : Container With Most Water

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

Java Solutions:

1.  

public class Solution {
    public int maxArea(int[] height) {
        int areas=0;
		int max_areas;
		for(int i=0,j=height.length-1;j>i;){
			max_areas=Math.min(height[i],height[j])*(j-i);
			if(max_areas>areas)
				areas=max_areas;
			if(height[i]>height[j]){
				j--;
			}else{
				i++;
			}
		}
		return areas;
    }
}


2.  After Improvement :

public class Solution {
    public int maxArea(int[] height) {
        int areas=0;
		int max_areas;
		int hl=height[0];
		int hr=height[height.length-1];
		for(int i=0,j=height.length-1;j>i;){
			max_areas=Math.min(hl,hr)*(j-i);
			if(max_areas>areas)
				areas=max_areas;
			if(hl>hr){
				while(i<j&&height[j]<=hr)
					j--;
				if(j>i)
					hr=height[j];
			}else{
				while(i<j&&height[i]<=hl)
					i++;
				if(j>i)
					hl=height[i];
			}
		}
		return areas;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章