计算堆栈搜索的空间复杂性

编程入门 行业动态 更新时间:2024-10-13 08:26:09
本文介绍了计算堆栈搜索的空间复杂性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在堆栈和搜索功能的情况下,我明白时间复杂度是 O(n)因为它取决于堆栈中元素的数量。在这种情况下,空间复杂度是多少?由于没有变量,或者根据元素的数量而使搜索消耗额外的内存,因此它将成为 O(1) O (n)?

Ex功能:

return stack.search(item)!= -1

编辑:

这是内置函数:

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; }

有人可以逐步细分如何计算这个空间复杂性

解决方案

对于 Stack.search 。

然而,简单看一下OpenJDK源代码,显示它是以 Vector.lastIndexOf() ,而是只有几个帮助变量的线性扫描。所以是的,O(1)空间在实践中。

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?

解决方案

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.

更多推荐

计算堆栈搜索的空间复杂性

本文发布于:2023-11-29 22:36:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647827.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:堆栈   复杂性   空间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!