力扣(十一)盛最多水的容器(双指针)

题目描述
力扣(十一)盛最多水的容器(双指针)_第1张图片
解题
思路:实质则求矩形面积,长为两线i的差值,宽为两线较短线的长(装水:木桶效应)。

public class Solution {
    public int MaxArea(int[] height) {
            int s = 0;
            for (int i = 0; i < height.Length ; i++)
            {
                for (int j = i+1 ; j < height.Length ; j++)
                {
                    s = Math.Max(Math.Min(height[l],height[r])*(r - l),s);
                }
            }
            return s;
    }
}

双for循环,所有可能都试一次,比较得出最大的面积。
官方解题

public int MaxArea(int[] height) {
            int s = 0;
            int l = 0;
            int r = height.Length-1;
            while (r > l)
            {
                s = Math.Max(Math.Min(height[l],height[r])*(r - l),s);
                if (height[r] > height[l])
                {
                    l++;
                }
                else
                {
                    r--;
                }
            }
            return s;
    }

知识点:双指针
①由两边向内移动;
②每次移动一边,移动较小的边(木桶效应,增加短板高度);
③双指针效率为双for循环效率十倍以上。

你可能感兴趣的:(c#)