[英]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;
}
先感謝您
要查找空間復雜度,請查看您聲明的變量,這些變量大於單個基本變量。 實際上,我相信您的空間復雜性將由數組auxilary
和Stack
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.