【问题标题】:Can someone explain to me the runtime of why Perfect Squares is O(sqrt(n))?有人可以向我解释为什么完美平方是 O(sqrt(n)) 的运行时间吗?
【发布时间】:2018-12-15 14:03:18
【问题描述】:

问题

  • 给定一个正整数 n,找出和为 n 的最小完美平方数(例如,1、4、9、16,...)。

    示例 1: 输入:n = 12 输出:3 解释:12 = 4 + 4 + 4

    示例 2: 输入:n = 13 输出:2 解释:13 = 4 + 9。

建议的解决方案 (BFS)

def numSquares(self, n):
    if n < 2:
        return n
    lst = []
    i = 1
    while i * i <= n:
        lst.append( i * i )
        i += 1
    cnt = 0
    toCheck = {n}
    while toCheck:
        cnt += 1
        temp = set()
        for x in toCheck:
            for y in lst:
                if x == y:
                    return cnt
                if x < y:
                    break
                temp.add(x-y)
        toCheck = temp

    return cnt

这个特定的 BFS 如何在 O(sqrt(n)) 中运行?因为我在想的是找到正方形需要 O(sqrt(n))。因为有2个for循环,(for y in lst1取O(sqrt(n)),for x in toCheck取O(sqrt(n)),不应该是O(n)吗??

【问题讨论】:

  • 你可能需要记住结果以达到 O(sqrt(n)) 复杂度

标签: algorithm runtime big-o perfect-square


【解决方案1】:

运行时间其实是Theta(n^(3/2))。根据Legendre's three-square theorem,对于整数ab,任何形式为4^a (8b + 7) 的整数都可以写成四个平方的和,而不是三个。让n 是这种整数。有小于nOmega(n) 数可以写成三个平方和,所以在while 循环的最后一次迭代中,toCheckTheta(n) 元素,lstTheta(n^(1/2))

【讨论】:

  • 美丽。我想知道这里是否会出现一些理论上的结果。
猜你喜欢
  • 1970-01-01
  • 2014-02-08
  • 2015-01-19
  • 2013-12-28
  • 1970-01-01
  • 2015-08-31
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
相关资源
最近更新 更多