# 11. Container With Most Water
個人最快的解法是用2個指標,一個從最左,一個從最右。左一右就是長度。面積就是長度*min([左],[右]),最次面積就存到comp,再跟max2比大小,comp比max2大就把comp指定給max2。
並判斷最左的值與最右的值大小,左比右小就把左向右移動一格; 若右比左小就把右向左移動一格(動的都是低的那根),以確保目前的長度的是最高的。
class Solution {
public int maxArea(int[] height) {
//two number ,the y is the shower one , power 2
//two number, the x is the one number and the two number index.
int font = 0;
int end = height.length-1;
int max2 = 0;
int comp = 0;
while(font < end){
comp = (end - font) *findMin( height[font] ,height[end] );
if(comp > max2){
max2= comp;
}
// System.out.println("font = " + font + " , end = " + end + " [f] = " + height[font] + " , [e] = " + height[end] + " ,comp = " + comp );
if(height[font] > height[end] ){
end--;
}else{
font++;
}
}
return max2;
//fast 27%
// if(height.length == 2){
// return 1* findMin( height[0] , height[1] );
// }
// int max2 = 0;
// int comp = 0;
// int cout = 0;
// for(int x = 0 ; x < height.length; x++){
// if(x > 0){
// cout = x;
// for(int y = 0 ; y < x ; y++){
// comp = cout * findMin( height[x] , height[y] );
// // System.out.println("x = " + x + " , h["+x+"]= "+ height[x] + " , y = " + y + " , h["+y+"]= "+ height[y] + " ,the comp = " + comp + " ,cout = " + cout );
// if(comp > max2 ){
// max2 = comp;
// }
// // System.out.println("--------------------------\n");
// cout--;
// }
// }
// }
// return max2;
}
public int findMin(int a, int b){
if(a > b){
return b;
}
return a;
}
}
Last updated
Was this helpful?