leetcode解题报告11. Container With Most Water

leetcode解题报告11. Container With Most Water

题目地址

难度是medium

题目描述

原文:
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.

我的思路

本质上:
输入一个数列,选择两个数字x和y,x和y在数列的位置差是d,假设x和y中较小者是x,那么结果就是x*d。现在问题是在数列中找出两个数x和y,使得结果最大。

基本思路:
暴力遍历两个数即可。但是可以优化提速。分别从数列两端开始遍历,这样两个数字的位置差是最大,现在假设两个数之中x为更小者,那当前最优的结果是x * d,那x端可以继续往内移动。因为d是越来越小的,那么往后即是出现x为更小者,其结果不会超过x * d,所以可以直接跳过。

我的代码

class Solution {
public:
    int maxArea(vector<int>& height) {
        int ans = 0;
        int cur;
        int left = 0;
        int right = height.size() - 1;
        while (right > left) {
            if (height[right] > height[left]) {
                cur = height[left] * (right - left);
                if (ans < cur) {
                    ans = cur;
                }
                left++;
            } else {
                cur = height[right] * (right - left);
                if (ans < cur) {
                    ans = cur;
                }
                right--;
            }
        }
        return ans;
    }
};

阅读官方题解

官方题解
就是我的如上的思路,从数列两端进行遍历。

思想核心总结

理解题目本身的特点。暴力解法一般是思路的入口,但是一般结合题目本身的特点,有对应的提升空间。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值