Leetcode Container With Most Water

12 篇文章 0 订阅

Leetcode Container With Most Water ,本算法的主要原理是从前两个方向进行扫描,保存最大的,并且在缩减范围,依据丢弃较小值的原则,相关cpp代码与测试如下:

#include<iostream>
#include<vector>
using namespace std;

// First we calculate the front till the end as the temporary value.
// And then we decrease the length of the array, by abandon the minimal of the
// two, because we can get the than: suppose the current length is m and the
// current V is "minimal * m", if we decrease the length of the container, we
// can never getting a lager result, so it is very wise to abandon the minimal
// value of the two.
class Solution {
public:
    int maxArea(vector<int>& height) {
        if (height.size() < 2) {
            return 0;
        }
        int len = height.size();
        int min = height[0] < height[len - 1]? height[0]: height[len - 1];
        int re = min * (len - 1);
        int low = 0;
        int high= len - 1;
        while (low < high) {
            min = height[low] < height[high]? height[low] : height[high];
            // Get the current higher value.
            if (re < min * (high - low)) {
                re = min * (high - low);
            }
            // Abandon the minimal value.
            if (height[low] <= height[high]) {
                low ++;
            } else {
                high --;
            }
        }
        return re;
    }
};

int main(int argc, char* argv[]) {
    Solution so;
    vector<int> test(4, 0);
    test[0] = 3;
    test[1] = 3;
    test[2] = 1;
    test[3] = 3;
    int re = so.maxArea(test);
    cout<<"result: "<<re<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值