11. Container With Most Water

来源:互联网 发布:varier 知乎 编辑:程序博客网 时间:2024/06/07 00:42

问题描述:

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 and n is at least 2.

一开始居然能没看懂题目,可见我是多需要刷题以及提高英语==

自己想没想出解法,但是看完别人的hint自己写了code调了几次才ac......其实这道题并不难,只是第一次做medium有点把它看的太高。

思路: 从数组两端向中间遍历直到相遇,用maxarea保存最大面积,然后每次把较小的向中间移动。

class Solution {    public static int maxArea(int[] height) {        int maxarea = 0;        for(int i = 0,j = height.length-1;i<j;){            int area = min(height[i],height[j])*(j-i);            if(maxarea<area)                maxarea = area;            if(height[i]<height[j])                i++;            else                j--;    }        return maxarea;    }    public static int min(int a, int b){        if(a<b)            return a;        else            return b;    }}
第一次fail的原因:

if(height[i]<height[j])                i++;            else                j--;
这里我一开始写的是:
if(height[i]<height[j])                i++; if(height[i]>=height[j])                j--;
二者看起来一样,但是其实if..else只会在两者之中执行一个,但是if..if则会分别判断,如果都满足就都执行!!条件语句这里要注意啊!!!
较快的解法:

public int maxArea(int[] height) {    int left = 0;int right = height.length-1;int max = 0,temp = 0;while(left<right) {if(height[left] > height[right]){temp = (right-left) * height[right];right--;}else{temp = (right-left) * height[left];left++;}max = max > temp ? max :temp;}return max;   }