LeetCode Solutions : Container With Most Water

来源:互联网 发布:linux dhcp分配主机名 编辑:程序博客网 时间:2024/06/06 17:05

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;    }}


0 0
原创粉丝点击