11. Container With Most Water

本人花费半年的时间总结的《Java面试指南》已拿腾讯等大厂offer,已开源在github ,欢迎star!

本文GitHub https://github.com/OUYANGSIHAI/JavaInterview 已收录,这是我花了6个月总结的一线大厂Java面试总结,本人已拿大厂offer,欢迎star

原文链接:blog.ouyangsihai.cn >> 11. Container With Most Water

本题来自 LeetCode:11. Container With Most Water[1]

题目描述

Given n non-negative integers a1, a2, …, an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

11. Container With Most Water

Note: You may not slant the container and n is at least 2.

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example:


Input: [1,8,6,2,5,4,8,3,7]
Output: 49

暴力法

题目分析

本题可以通过暴力法来解答,采用双层循环,迭代出最大值。

题目解答


class Solution {
    public int maxArea(int[] height) {
        int max = Integer.MIN_VALUE;
        for(int i = 0; i  height.length - 1; i ++) {
            for(int j = i + 1; j  height.length; j ++ ) {
                max = Math.max(max, Math.min(height[i], height[j]) * (j - i));
            }
        }
        return max;
    }
}

复杂度分析:
时间复杂度: O(n ^ 2)
空间复杂度: O(1)

双指针

题目分析

注意到,要使面积最大,在相同的条件下,要么是左右两条边之间的距离越长,要么是左右两条边的最小长度越大。
而如果是左右两条边之间的距离变短的情况下,那么就需要左右两条边的最小长度越大,面积才有可能变大。

题目解答


class Solution {
    public int maxArea(int[] height) {
        int left = 0;
        int right = height.length - 1;

        int max = Integer.MIN_VALUE;

        while(left  right) {
            // 比较最大值
            max = Math.max(max, Math.min(height[left], height[right]) * (right - left));
            if(height[left]  height[right]) {
                // 若左边长度小于右边长度,则收缩左边
                left ++;
            } else {
                // 否则收缩右边
                right --;
            }
        }

        return max;
    }
}

复杂度分析:
时间复杂度: O(n)
空间复杂度: O(1)

参考资料

  1. Container With Most Water: https://leetcode-cn.com/problems/container-with-most-water

原文始发于微信公众号(xiaogan的技术博客):

本人花费半年的时间总结的《Java面试指南》已拿腾讯等大厂offer,已开源在github ,欢迎star!

本文GitHub https://github.com/OUYANGSIHAI/JavaInterview 已收录,这是我花了6个月总结的一线大厂Java面试总结,本人已拿大厂offer,欢迎star

原文链接:blog.ouyangsihai.cn >> 11. Container With Most Water


 上一篇
38. Count and Say 38. Count and Say
本题来自 LeetCode:38. Count and Say[1] 题目描述The count-and-say sequence is the sequence of integers with the first five terms
2021-04-05
下一篇 
Java反射的那些事(1)- 泛型和类型 Java反射的那些事(1)- 泛型和类型
最近在做一个 Map数据结构转换为指定 Class类型的工具,涉及了反射相关的知识点。借这个机会,整理下这方面的知识。这篇文章先来了解下泛型和Type类型的知识点。  Java JDK从1.5开始引入泛型这个概念,在这之前只有原始类型而没有
2021-04-05