时间和空间复杂性 - 用于内部循环的循环

发布于 2025-01-25 19:19:17 字数 723 浏览 4 评论 0原文

时间是什么时候&以下代码的复杂性?

function SortFunction (entries):
    sorted_entries = {}
    
    while entries is not empty: 
        smallest entry = entries [0]
        
        foreach entry in entries:
            if (entry <smallest_entry): 
                smallest entry = entry
                
        sorted_entries.add(smallest _entry)
        entries.remove(smallest entry)
        
    return sorted_entries

我认为复杂性的时间可能是O(n^2),但是在互联网上对于类似情况有不同的答案,所以我感到困惑。 那空间复杂性呢?

关于此主题的一个额外的小问题:

function PrintCol():
    colours = { "Red", "Green", "Blue", "Grey" }
    foreach colour in colours: 
        print(colour)

由于只有一个循环,这里的时间复杂性是o(n),对吗? 空间复杂性?

What is the time & complexity of the code below?

function SortFunction (entries):
    sorted_entries = {}
    
    while entries is not empty: 
        smallest entry = entries [0]
        
        foreach entry in entries:
            if (entry <smallest_entry): 
                smallest entry = entry
                
        sorted_entries.add(smallest _entry)
        entries.remove(smallest entry)
        
    return sorted_entries

I thought the time complexisty could be O(n^2) but there are different answers on the internet for similar situations, so I was confused.
And what about the space complexity?

And an extra small question about this topic:

function PrintCol():
    colours = { "Red", "Green", "Blue", "Grey" }
    foreach colour in colours: 
        print(colour)

The time complexity here is O(n) since there is only one loop, right?
Space complexity?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忱杏 2025-02-01 19:19:17

循环时有n迭代,每次迭代的成本为o(n)。这是假设在线性时间内运行的添加和删除方法。然后总成本为o(n^2)。

您的第二个程序将花费O(n)。

There are n iterations of the outer while loop, and the cost of each iteration is O(n). This is assuming that the add and remove methods each run in linear time. The total cost is then O(n^2).

Your second program would have cost O(n).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文