问题
having a bit of issues understanding space complexity for a method.
In the case of a stack and a search function, I understand that time complexity is O(n) since it depends on the amount of elements in the stack. What would the space complexity be in this case? Would it be O(1) since there are no variables or does the search consume extra memory based off the amount of elements and cause it to be O(n)?
Ex Function:
return stack.search(item) != -1
Edit:
Here is the built in function in question:
public synchronized int search(Object o) {
int i = lastIndexOf(o);
if (i >= 0) {
return size() - i;
}
return -1;
}
public synchronized int lastIndexOf(Object o, int index) {
if (index >= elementCount)
throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
if (o == null) {
for (int i = index; i >= 0; i--)
if (elementData[i]==null)
return i;
} else {
for (int i = index; i >= 0; i--)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
Can someone provide a step by step breakdown of how to calculate space complexity for this?
回答1:
Neither time nor space complexity appears to be documented in the Javadoc for Stack.search.
However, a brief look at the OpenJDK source code shows that it's implemented in terms of Vector.lastIndexOf(), which in turn is a linear scan with just a couple of helper variables. So yes, O(1) space in practice.
回答2:
I didn't get the point of O(n) you mentioned. Stack is both O(1) time for storing(push) and O(1) for retrieving(pop).
There is no operation defined as search for proper stack data structure. Stack simply works in a Last In First Out fashion. When you add a new item, you add it on top, when you retrieve an item, you only have one option, the top. So, both push and pop operations have time complexity of O(1).
To talk about space complexity, we need to know what the problem is. If you need to store n items in stack same time, then space complexity is O(n). But you can store n items, in O(1) space too. You can push and pop every item, therefore you use only 1 space.
So what's happening in this Java implementation?
It seems they simply implemented search method, just in case, maybe someone would ever need, I don't know. But it simply violates stack contract.
If you use a search on stack, then it's time complexity is O(n) and it's no longer a stack actually. Space complexity is O(1), you guessed right. It would only use 1 extra variable, it doesn't scale up with stack size.
Edit: Sorry, I didn't realize this is a Java's stack implementation specific question. I'm editing my answer to cover Java implementation.
来源:https://stackoverflow.com/questions/34479939/calculating-space-complexity-of-stack-search