LeetCode-11~Container with Most Water

来源:互联网 发布:淘宝怎么设置降价提醒 编辑:程序博客网 时间:2024/05/17 21:26

传统的双指针解法仍然存在一些重复计算的问题,因此我改进了此方法多加入了一重判断,效率上提高了不少

public int maxArea2(int[] height) {        int dFlag = 0;//1表示前一次左进,2表示右退        int tmp_left = 0;//上次经过计算的水桶的左值        int tmp_right = 0;//上次经过计算的水桶的右值        int max = 0;        int left = 0;        int tmpHeight = 0;        int right = height.length - 1;        while (left < right) {            if (dFlag == 1) {                if (height[left] <= tmp_left) {                    left++;                    continue;                }            }            if (dFlag == 2) {                if (height[right] <= tmp_right) {                    right--;                    continue;                }            }            tmp_left = height[left];            tmp_right = height[right];            max = Math.max(max, Math.min(height[left],height[right])*(right - left));            if (height[left] < height[right]) {                left++;                dFlag = 1;            } else {                right--;                dFlag = 2;            }        }        return max ;    }
原创粉丝点击