微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

捕获雨水算法复杂度

如何解决捕获雨水算法复杂度

试图解决 Trapping Rain Water 问题,但不明白为什么我的解决方案没有通过复杂性检查:

    public int Trap(int[] height) {
        int res = 0;
        int chk = 0;
        for(int i = 1; i < height.Length; i++){
            chk = Math.Min(height[..i].Max(),height[i..].Max())-height[i];
            if(chk > 0){
                res += chk;
            }
        }
        return res;
    }
Compile:    0.024s
Execute:    0.85s
Memory: 3.90Mb
cpu:    0.874s

但是这个(推荐)通过了:

    public int Trap(int[] land) {
       var wall = 0;
        var water = new int[land.Length];
        for(var i = 0; i < water.Length; i++) {
            wall = Math.Max(wall,land[i]);
            water[i] = wall - land[i];
        }
        wall = 0;
        var sum = 0;
        for(var i = water.Length - 1; i >= 0; i--) {
            wall = Math.Max(wall,land[i]);
            water[i] = Math.Min(water[i],wall - land[i]);
            sum += water[i];
        }
        return sum;
    }
Compile:    0.024s
Execute:    0.03s
Memory: 0b
cpu:    0.054s

为什么差别这么大?是因为数组 slice[..i] 吗?

解决方法

数组切片操作的时间复杂度为O(N)
因此,您的代码的总时间复杂度变为 O(N2)
这就是 TLE 的原因。

虽然推荐的代码仅在 O(N) 时间复杂度内解决该问题。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。