前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode】11. Container With Most Water | 盛最多水的容器

【leetcode】11. Container With Most Water | 盛最多水的容器

作者头像
帅地
发布2019-06-06 15:14:31
5810
发布2019-06-06 15:14:31
举报
文章被收录于专栏:苦逼的码农苦逼的码农

题目描述

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.

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.

如果你看不懂英文,我给你提供了中文版的链接:https://leetcode-cn.com/problems/container-with-most-water/ 还有,点击阅读原文可以进入leetcode原题

示例

代码语言:javascript
复制
Input: [1,8,6,2,5,4,8,3,7]
Output: 4

难度系数

Medium

解答

这个其实就相当于算坐标之间所围成的面积,一种比较简单的方法就是算出所有坐标的组合,然后看看哪两个围成的面积比较大,时间复杂度是O(n2)。代码如下:

代码语言:javascript
复制
    public int maxArea(int[] height) {
        int max = 0;

        for (int i = 0; i < height.length; i++) {
            int temp = 0;
            for (int j = i + 1; j < height.length; j++) {
                // 算出所围成的面积
                max = Math.max(max,(j-i)*Math.min(height[i], height[j]));
            }
        }
        return max;
    }

不知道大家有没做过之前的两数之和所用到的双指针法,就是用两个指针从数组的左右两边往中间遍历,其实我们这道题就可以采用这种方法了。其思想是:用两个指针 left 和 right 分别指向数组的最左边和最右边,如果arr[left] > arr[right],则让右边的指针向左移动,否则,让左边的指针向右移动。

每次移动都会计算出此时围成的面积,并且用一个变量来记录最大的面积。直接看代码吧:

代码语言:javascript
复制
    //双指针的模式做
    public int maxArea2(int[] height) {
        int left = 0;
        int right = height.length - 1;
        int max = 0;
        while (right > left) {
            max = Math.max(max,(right-left)*Math.min(height[right], height[left]));
            if(height[right]>height[left])
                left++;
            else
                right--;
        }
        return max;
    }

这个方式的时间复杂度是 O(n)。这种双指针法在很多地方都有用到,大家可以多试着去使用。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-04-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 帅地玩编程 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 示例
  • 难度系数
  • 解答
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档