LeetCode 11 Container With Most Water

本文探讨了在给定一组非负整数表示的垂直线的情况下,如何使用双指针法优化求解最大容器容量的问题。通过避免暴力法的高复杂度,我们提出了一种线性时间复杂度的解决方案,显著提高了效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

解法思路:题目大意是以x轴 ,两个以顶点在(iai)、(j, aj)到x轴的垂直直线所围成的凹槽的面积的最大值。

暴力法,O(n^2) 的复杂度,两层循环遍历所有节点,找到最大值。但是明显超时了,因此,需要改进。

在这里设置两个指针,分别从最左边和最右边遍历。然后进行判断,若出现左边低于右边高度时,将左边指针加1.若出现左边高于右边的时候,则右边加1.
这里这样做的原因是,当出现较低的高度的时候,替换这个低的高度,从而遍历寻找高的高度来提高面积。如果以相反的做法,则不能提高面积。
暴力法代码如下:
int maxArea1(int* height, int heightSize){
	int max = 0;
	for (int i = 0; i < heightSize; i++){
		int t = heightSize - 1;
		while (t>=i)
		{
			int h = height[i]>height[t] ? height[t] : height[i];
			int temp = (t-i)*h;
			if (temp >= max){
				max = temp;
			}
			t--;
		}
	}
	return max;
}

双指针代码如下:复杂度O(n)
int maxArea(int *height, int heightSize){
	int max = 0;
	int left = 0;
	int right = heightSize-1;
	while (left < right){
		int h = height[left]>height[right] ? height[right] : height[left];
		int temp = (right - left)*h;
		if (temp >= max){
			max = temp;
		}
		if (height[left] > height[right]){
			right--;
		}
		else{
			left++;
		}
	}
	return max;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值