Container With Most Water—LeetCode

318 阅读1分钟

题目描述

思想

利用两个指针,一个从开始位置向前遍历,一个从结束位置向前遍历

不断比较两个指针对应位置的高度,将低的那个指针对应的高度换掉,并计算此时的面积,在这个计算过程中,总是有一个最大的面积存在的

代码实现

class Solution {
    public int maxArea(int[] height) {
        int start = 0;
        int end = height.length-1;
        int max = 0;
        int temp = 0;
        while(start != end){
            temp = (end - start) * Math.min(height[end], height[start]);
            if(temp > max){
                max = temp;
            }
            if(height[start] > height[end]){
                end--;
            }else{
                start++;
            }
        }
        return max;
        
    }
}