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


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