LeetCode 11. Container With Most Water(最大盛水器)

题目描述:

    Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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轴较短垂直线高度)。

LeetCode 11

    思路:这题采用双指针法。假设垂直线数量为n,那么我们初始化指针left = 0、right=n-1(即指向第一条、最后一条垂直线),得到两者较短高度,计算获得面积。如果left指针右边的垂直线高度比当前最短高度低,则left右移(因为left右移之后,left、right的X轴间隔变小,要想获得更大面积,高度必须增加);同理,如果right指针左边的垂直线高度比当前最短高度低,则right左移。与此同时,更新最大面积。
    时间复杂度为O(n)。

代码:

#include <bits/stdc++.h>

using namespace std;

// two pointers
class Solution {
public:
    int maxArea(vector<int>& height) {
        int n = height.size();
		// Exceptional Case: 
		if(n <= 1){
			return 0;
		}
		int ans = 0;
		int left = 0, right = n - 1;
		while(left < right){
			// debug
			// cout << "left: " << left << ", right: " << right << endl;
			int min_height = min(height[left], height[right]);
			ans = max(ans, min_height * (right - left));
			while(left <= n - 2 && height[left] <= min_height){
				left++;
			}
			while(right >= 1 && height[right] <= min_height){
				right--;
			}
		}
		return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值