我的算法的时间和空间复杂性是什么?

发布于 2025-02-06 21:46:44 字数 566 浏览 0 评论 0原文


当我学习数据结构和算法时,我对计算算法的时间和空间的复杂性感到非常困惑。

这个问题来自 leetcode

def product_except_self(nums):
    result = []
    start = 0
    while start != len(nums):
        total = 1
        for i in nums:
            if i != nums[start]:
                total *= i
        result.append(total)
        start += 1
    return result

因此,我的计算复杂性是
时间复杂性:o(n^2)
空间复杂性:o(n)

As I am learning data structure and algorithms, I am very confused about computing the complexity of time and space of the algorithm.

This problem is from the leetcode.

def product_except_self(nums):
    result = []
    start = 0
    while start != len(nums):
        total = 1
        for i in nums:
            if i != nums[start]:
                total *= i
        result.append(total)
        start += 1
    return result

So, my computation complexities are,
Time Complexity: O(n^2)
Space Complexity: O(n)

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

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

发布评论

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

评论(1

遮云壑 2025-02-13 21:46:44
def product_except_self(nums):
    result = [] // in the worst case you would need to put all array in the result array, what give O(n) space complexity. 
    start = 0
    while start != len(nums): // O(n) complexity
        total = 1
        for i in nums: // One more loop that gave additional O(n) complexity, in result we have O(n^2)
            if i != nums[start]:
                total *= i
        result.append(total)
        start += 1
    return result

是的,你有正确的假设

def product_except_self(nums):
    result = [] // in the worst case you would need to put all array in the result array, what give O(n) space complexity. 
    start = 0
    while start != len(nums): // O(n) complexity
        total = 1
        for i in nums: // One more loop that gave additional O(n) complexity, in result we have O(n^2)
            if i != nums[start]:
                total *= i
        result.append(total)
        start += 1
    return result

Yep, you have the correct assumption

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