常考数据结构与算法:容器盛水问题

题目描述

给定一个整形数组arr,已知其中所有的值都是非负的,将这个数组看作一个容器,请返回容器能装多少水。

示例

输入

[3,1,2,5,2,4]

返回值

5

在这里插入图片描述

思路

能装多少水是由左右两边较低的边决定的,因此采用双指针,从开头和最后向中间靠拢,当位置i的数小于较低边表示可以装水。当位置i的数大于较低边时,更新较低边为位置i的值。

public class MaxWaterStruct {
    public static void main(String[] args) {
        int[] arr = {3,1,2,5,2,4};
        MaxWaterStruct maxWaterStruct = new MaxWaterStruct();
        long l = maxWaterStruct.maxWater(arr);
        System.out.println(l);
    }

    public long maxWater (int[] arr) {
        // write code here
        if(arr.length < 1){
            return 0;
        }
        int i = 0; // 左指针
        int j = arr.length - 1; // 右指针
        int maxLeft = arr[i]; //桶左边的长度
        int maxRight = arr[j]; // 桶右边的长度
        long ret = 0L; // 盛水总量
        while(i < j){
            // 较低边为左边
            if(maxLeft < maxRight){
                i++;
                // 当前位置i小于大于较低边,更新较低边的值,小于装水
                if(arr[i] > maxLeft){
                    maxLeft = arr[i];
                }else{
                    ret += maxLeft - arr[i];
                }
            }else{
                // 较低边为右边
                j--;
                // 当前位置i小于大于较低边,更新较低边的值,小于装水
                if(arr[j] > maxRight){
                    maxRight = arr[j];
                }else{
                    ret += maxRight - arr[j];
                }
            }
        }
        return ret;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37564426/article/details/114087656