leetcode11:Container With Most Water

本文介绍了一种解决LeetCode 11题目的算法实现,该问题要求在给定的整数数组中找到两个高度,使得这两个高度与x轴构成的水池能够容纳最多的水。通过使用双指针技术,逐步逼近最优解。

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

我的leetcode代码已经放入github:https://github.com/gaohongbin/leetcode


题目:给出一个非负整数数组,数组中的数代表一个栏杆,寻找两个栏杆和x轴形成一个水池,找出能装水最多的两个栏杆。

  假如给出的例子是height = {1,2,3,4,5,6,7,8,9},则height[4]=5,height[8]=9,则形成的水池是(9-5)*5=20


思路:先用两个指针,一个low一个hight,一个指向数组开头,一个指向数组结尾,则我们要找的两个栏杆肯定在这两个指针之间,当height[low]<height[high], 则low++,因为如果high--的话,装的水肯定不会比现在多。如果height[low]>height[high],则high--。如果height[low]==height[high],则low++且high--; 用result来记录过程中最大的装水量返回即可。


代码:

/**
 * 题目:给出一个非负整数数组,数组中的数代表一个栏杆,寻找两个栏杆和x轴形成一个水池,找出能装水最多的两个栏杆。
 * 假如给出的例子是height = {1,2,3,4,5,6,7,8,9},则height[4]=5,height[8]=9,则形成的水池是(9-5)*5=20
 * @author hongbin.gao
 * 思路:先用两个指针,一个low一个hight,一个指向数组开头,一个指向数组结尾,则我们要找的两个栏杆肯定在这两个指针之间,当height[low]<height[high],
 * 则low++,因为如果high--的话,装的水肯定不会比现在多。如果height[low]>height[high],则high--。如果height[low]==height[high],则low++且high--
 * 用result来记录过程中最大的装水量返回即可。
 */

public class Leetcode11 {
	
	 public static int maxArea(int[] height) {
	       if(height == null)
	    	   return 0;
	       
	       int length = height.length;
	       if(length < 1)
	    	   return 0;
	       
	       int low = 0;
	       int high = length-1;
	       int result = 0;
	       while(low<high){
	    	   if(height[low]<height[high] && height[low]*(high-low)>result)
	    		   result = height[low]*(high-low);
	    	   else if(height[low]>=height[high] && height[high]*(high-low)>result)
	    		   result = height[high]*(high-low);
	    	   
	    	   if(height[low]<height[high])
	    		   low++;
	    	   else if(height[low]>height[high])
	    		   high--;
	    	   else{
	    		   low++;
	    		   high--;
	    	   }
	       }
	       return result;
	    }
	 
	 public static void main(String[] args){
		int[] height = {1,2,3,4,5,6,7,8,9};
		int result = maxArea(height);
		System.out.println(result);
	 }                      
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值