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.
Note: You may not slant the container and n is at least 2.
Subscribe to see which companies asked this question.
題目
給定 n 個(gè)非負(fù)整數(shù) a1, a2, ..., an, 每個(gè)數(shù)代表了坐標(biāo)中的一個(gè)點(diǎn) (i, ai)。畫 n 條垂直線恋拷,使得 i 垂直線的兩個(gè)端點(diǎn)分別為(i, ai)和(i, 0)叹誉。找到兩條線,使得其與 x 軸共同構(gòu)成一個(gè)容器狂窑,以容納最多水走越。
注意事項(xiàng)
容器不可傾斜杏糙。
樣例
給出[1,3,2], 最大的儲(chǔ)水面積是2
分析
用兩根指針一頭一尾,分別計(jì)算面積浆熔,然后選取高度小的那邊向中間移動(dòng)本辐,因?yàn)檫@樣才可能存在更大的面積,更新最大的面積医增,最后就是結(jié)果慎皱。
代碼
public class Solution {
/**
* @param heights: an array of integers
* @return: an integer
*/
int computeArea(int left, int right, int[] heights) {
return (right-left)*Math.min(heights[left], heights[right]);
}
public int maxArea(int[] heights) {
//兩根指針,一頭一尾計(jì)算叶骨,短的那根指針向中間移動(dòng)茫多,因?yàn)橹挥羞@種情況才存在更大的情況
int left = 0, right = heights.length-1;
int res = 0;
while(left < right) {
res = Math.max(res, computeArea(left,right,heights));
if(heights[left] < heights[right]) {
left++;
//如果小于則不必要計(jì)算,直接跳過
while(heights[left] <= heights[left-1] && left<right)
left++;
}
else {
right--;
while(heights[right] <= heights[right+1] && left <right)
right--;
}
}
return res;
}
}