繁体   English   中英

查找给定Java代码的时间和空间复杂度

[英]finding time and space complexity of the given java code

您好,我需要找到程序的时间和空间复杂度,请提供帮助,如果可能,请提出可以执行的优化建议,...................... ................................................... ................................................... ................................................... .............

public class Sol {
    public int findMaxRectangleArea(int [][] as) {
        if(as.length == 0)
       return 0;
    int[][] auxillary = new int[as.length][as[0].length];
        for(int i = 0; i < as.length; ++i) {
            for(int j = 0; j < as[i].length; ++j) {
            auxillary[i][j] = Character.getNumericValue(as[i][j]);
        }
        }
        for(int i = 1; i < auxillary.length; ++i) {
        for(int j = 0; j < auxillary[i].length; ++j) {
            if(auxillary[i][j] == 1)
                    auxillary[i][j] = auxillary[i-1][j] + 1;
            }
        }

    int max = 0;
        for(int i = 0; i < auxillary.length; ++i) {
            max = Math.max(max, largestRectangleArea(auxillary[i]));
        }
        return max;
    }

    private int largestRectangleArea(int[] height) {
        Stack<Integer> stack =
        new Stack<Integer>();
        int max = 0;
        int i = 0;
        while(i < height.length) {
            if(stack.isEmpty() ||
                height[i] >= stack.peek()) {
                stack.push(height[i]);
            i++;
            }
            else {
            int count = 0;
            while(!stack.isEmpty() &&
                stack.peek() > height[i]) {
                    count++;
                    int top = stack.pop();
                max = Math.max(max, top * count);
                }
            for(int j = 0; j < count + 1; ++j) {
                    stack.push(height[i]);
                }
                i++;
            }
        }

        int count = 0;
        while(!stack.isEmpty()) {
            count++;
            max = Math.max(max, stack.pop() * count);
        }
        return max;
    }

先感谢您

要查找空间复杂度,请查看您声明的变量,这些变量大于单个基本变量。 实际上,我相信您的空间复杂性将由数组auxilaryStack stack 第一个的大小非常清楚,我不完全理解第二个的大小,但是我看到它的大小永远不会大于数组中的一个。 所以我要说的是空间复杂度是O(size of(auxilary))O(N * M) ,其中N=as.length()M = as[0].length

现在,时间复杂度有点棘手。 您在整个auxilary阵列上有两个周期,因此请确保时间复杂度至少为O( N * M) 你也有一个循环调用largestRectangleArea对于每一行auxilary 如果我在此函数中正确获取了代码,则该函数似乎又是线性的,但是我不确定在这里。 由于您更了解逻辑,因此您可能可以更好地计算其复杂性。

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM