[LeetCode] Container With Most Water

这道题初看要遍历所有可能就能求解,但是复杂度要O(n^2),系统肯定会判超时。大概这么多年应试教育的结果吧,所以继续思考:很明显两边的情况是底最长,往中间缩的话有可能高度的变化会弥补底边的缩小,所以只考虑高度变长的情况即可。当两边确定后,需要从短的那边往中间缩进,就能遍历所有的可能了。当然每次缩进后都要重新判断短的那边。其实是求面积的问题,说成是装水,最终我还是打算返回矩形面积,应试教育的后果就是即使题出错了也能将错就错,最终给出出题人想要的答案。很激动的是这道题居然一次通过了,说明这道题难度系数不高。

class Solution {
public:
    int maxArea(vector<int> &height) {
		int length = height.size();
		int left = height[0];
		int right = height[length - 1];

		bool shiftRight = false;
		int maxArea = 0;
		if (left < right) {
			maxArea = left * (length - 1);
			shiftRight = true;
		}
		else {
			maxArea = right * (length - 1);
		}

		int index_left = 0;
		int index_right = length - 1;
		while (index_left < index_right) {
			int newMax = 0;
			if (shiftRight) {
				if (height[++index_left] > left) {
					left = height[index_left];
				}
				else {
					continue;
				}
			}
			else {
				if (height[--index_right] > right) {
					right = height[index_right];
				}
				else {
					continue;
				}
			}

			if (right > left) {
				newMax = left * (index_right - index_left);
				shiftRight = true;
			}
			else {
				newMax = right * (index_right - index_left);
				shiftRight = false;
			}
			maxArea = (newMax > maxArea) ? newMax : maxArea;
		}
		return maxArea;
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值