11. Container With Most Water--思路详解

48 篇文章 0 订阅
43 篇文章 0 订阅

题目

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.

翻译

给定n个非负整数a1,a2,…, an,每一个整数表示一点在(i,ai)的点。然后垂直于x轴向下划线。然后求线(i,ai)和(j,aj)还有x轴所能容纳最大的水量

分析

1,首先也是暴力法,即计算每两个线之间的容量。发现超时,因为此时的时间复杂度为O(n^2)

代码1

class Solution {
public:
    int maxArea(vector<int>& height) {
        int len = height.size();
        int max = 0;
        for(int i = 0; i < len; i ++){
            for(int j = i+1;j < len; j++){
                int tmp = std::min(height[i],height[j])*(j-i);
                if(tmp > max){
                    max = tmp;
                }
            }
        }
        return max;
    }
};

2,经过看比人博客发现自己方法太糙了。
比如A[] = [1,2,5,3,2,2,4]。使用双指针法。start ,end
因为比如start = 0 end = 6时,容积为1*6。如果end -1 。此时容积为1*5。即当前容积有其中最小值决定。
所以
如果A[start] < A[end]. start ++;
如果A[start] > A[end] end –;
然后计算当前start和end之间的最大值。更新max

代码

class Solution {
public:
    int maxArea(vector<int>& height) {
        int len = height.size();
        int max = 0;
        int start = 0;
        int end = len -1;
        while(start < len){
            int tmp = 0;
            if(height[start] > height[end]){
                tmp = height[end]*(end-start);
                end --;
            }else{
                tmp = height[start]*(end-start);
                start++;
            }

            if(tmp > max){
                max = tmp;
            }
        }
        return max;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值