道阻且长,行则将至,走慢一点没关系,不停下就好了.|

Ac_c0mpany丶

园龄:3年7个月粉丝:6关注:3

2023-12-02 10:26阅读: 5评论: 0推荐: 0

[LeetCode Hot 100] LeetCode11. 盛最多的水

题目描述

方法一:暴力,超出时间限制

模拟所有情况,记录最大的体积值。
体积 = Math.min(height[i], height[j]) * (j - i)

class Solution {
    public int maxArea(int[] height) {
        int res = Integer.MIN_VALUE;

        for (int i = 0; i < height.length; i ++) {
            for (int j = i + 1; j < height.length; j ++) {
                int edge = Math.min(height[i], height[j]);
                res = Math.max(res, (j - i) * edge);
            }
        }
        return res;
    }
}

时间复杂度O(n2)

方法二:双指针

思路

  • 初始化: 双指针 iii , jjj 分列水槽左右两端;
  • 循环收窄: 直至双指针相遇时跳出;
    • 更新面积最大值:res;
    • 选定两板高度中的短板,向中间收窄一格;
  • 返回值:返回面积最大值res即可;

木桶容量由短板决定, 移动长板的话, 水面高度不可能再上升, 而宽度变小了, 所以只有通过移动短板, 才有可能使水位上升.

class Solution {
    public int maxArea(int[] height) {
        int i = 0, j = height.length - 1;
        int res = Integer.MIN_VALUE;

        while (i <= j) {
            int area = (j - i) * Math.min(height[i], height[j]);
            if (area > res) {
                res = area;
            }
            if (height[i] <= height[j]) {
                i ++;
            }else if (height[i] > height[j]) {
                j --;
            }
        }
        return res;
    }
}

本文作者:Ac_c0mpany丶

本文链接:https://www.cnblogs.com/keyongkang/p/17871320.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Ac_c0mpany丶  阅读(5)  评论(0编辑  收藏  举报
历史上的今天:
2022-12-02 Java生成UUID
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 You Are My Sunshine REOL
You Are My Sunshine - REOL
00:00 / 00:00
An audio error has occurred.

作曲 : Traditional

You are my sunshine

My only sunshine.

You make me happy

When skies are gray.

You'll never know, dear,

How much I love you.

Please don't take my sunshine away

The other night, dear,

When I lay sleeping

I dreamed I held you in my arms.

When I awoke, dear,

I was mistaken

So I hung my head and cried.

You are my sunshine,

My only sunshine.

You make me happy

When skies are gray.

You'll never know, dear,

How much I love you.

Please don't take my sunshine away.

You are my sunshine,

My only sunshine

You make me happy

When skies are gray.

You'll never know, dear

How much I love you

Please don't take my sunshine away

Please don't take my sunshine away.

Please don't take my sunshine away.