【LeetCode OJ 011】Container With Most Water

链接:https://leetcode.com/problems/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.

AC,Runtime: 6 ms

代码实例:

public class Solution
{
	 public int maxArea(int[] height)
	 {
		 int maxArea=0;
		 int n=height.length;
		 int left=0;
		 int right=n-1;
		 while(left<right)
		 {
			 int temp;
			 temp=Math.min(height[left], height[right])*(right-left);//取两边的最小值
			 if(maxArea<temp)
				 maxArea=temp;
			 if(height[left]<height[right]) //如果左边小,说明左边是瓶颈,应该向右寻找最大值
				 left++;
			 else //反之向左寻找
				 right--;
		 }
		 return maxArea;  
	 }
}


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