• [LeetCode] 11. Container With Most Water ☆☆


    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.

    解法:

      最大盛水量取决于两边中较短的那条边,而且如果将较短的边换为更短边的话,盛水量只会变少。所以我们可以用两个头尾指针,计算出当前最大的盛水量后,将较短的边向中间移,因为我们想看看能不能把较短的边换长一点。这样一直计算到指针重合为止就行了。

    public class Solution {
        public int maxArea(int[] height) {
            int max = 0;
            int i = 0;
            int j = height.length - 1;
            while (i < j) {
                int lower = Math.min(height[i], height[j]);
                max = Math.max(lower * (j - i), max);
                if (height[i] < height[j]) i++;
                else j--;
            }
            return max;
        }
    }

      改进:如果较短的边向中间移动后,新的边比原来的短,可以直接跳过,找下一条边,减少一些计算量。

    public class Solution {
        public int maxArea(int[] height) {
            int max = 0;
            int i = 0;
            int j = height.length - 1;
            while (i < j) {
                int lower = Math.min(height[i], height[j]);
                max = Math.max(lower * (j - i), max);
                if (height[i] < height[j])
                    while (i < j && height[i] <= lower) i++;
                else
                    while (i < j && height[j] <= lower) j--;
            }
            return max;
        }
    }
  • 相关阅读:
    快乐前端-图片预加载
    浅谈canvas绘画王者荣耀--雷达图
    浅谈CSS3动画的凌波微步--steps()
    车大棒浅谈jQuery源码(二)
    车大棒浅谈jQuery源码(一)
    车大棒浅谈for循环+canvas实现黑客帝国矩形阵
    浅谈JavaScript 函数作用域当中的“提升”现象
    清除浮动塌陷的4种经典套路
    可以看电影的微信公众号
    Mac安装protobuf编译Java
  • 原文地址:https://www.cnblogs.com/strugglion/p/6402253.html
Copyright © 2020-2023  润新知