LeetCode(困难)接雨水(c#)

题目为 给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。
在这里插入图片描述
思路将数组的位置以及值存储到键值对中,并排序。找到最高点,分别向左、右计算水量,水量为最低的边乘以距离。减去两边之间的数组值,代码如下

		public int Trap(int[] height)
        {
            if (height==null||height.Count()==0)
            {
                return 0;
            }
            int count = height.Count();
            Dictionary<int, int> dic = new Dictionary<int, int>();
            for (int i = 0; i < count; i++)
            {
                dic.Add(i,height[i]);
            }
            Dictionary<int, int> sort= dic.OrderByDescending(e => e.Value).ToDictionary(p => p.Key, o => o.Value);
            //左侧体积计算
            int res = 0;
            int maxTempPlace = sort.First().Key;
            int maxTempPlaceRIght = sort.First().Key;
            foreach (var item in sort)
            {
                if (item.Key < maxTempPlace)
                {
                    res += (maxTempPlace - item.Key-1) * height[item.Key];
                    for (int i = item.Key + 1; i < maxTempPlace; i++)
                    {
                        res -= height[i];
                    }
                    maxTempPlace = item.Key;
                }
                else if (item.Key > maxTempPlaceRIght)
                {
                    res += (item.Key - maxTempPlaceRIght - 1) * height[item.Key];
                    for (int i = maxTempPlaceRIght + 1; i < item.Key; i++)
                    {
                        res -= height[i];
                    }
                    maxTempPlaceRIght = item.Key;
                }
            }
            return res;
        }

第二种是双指针,左右两侧同时向中间移动,如外侧比内测大,则相邻相减为贡献的水的体积。代码如下

		public int Trap(int[] height)
        {
            int left = 0, right = height.Length - 1;
            int res = 0;
            int leftMax = 0, rightMax = 0;
            //比较两个指针,移动小的那个向中间移动
            while (left<right)
            {
                if (height[left]<height[right])
                {
                    if (leftMax < height[left])
                    {
                        leftMax= height[left];
                    }
                    else
                    {
                        //差值为可接水的体积
                        res += (leftMax-height[left]);
                    }
                    left++;
                }
                else
                {
                    if (rightMax < height[right])
                    {
                        rightMax = height[right];
                    }
                    else
                    {
                        res += (rightMax - height[right]);
                    }
                    right--;
                }
            }
            return res;
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值