【问题标题】:what is the time complexity of this NumberComplement function?这个 NumberComplement 函数的时间复杂度是多少?
【发布时间】:2016-10-26 06:44:40
【问题描述】:

函数 NumberComplement(num) 接受一个十进制数,将其转换为二进制数,然后将每个二进制数反转,然后将反转的二进制数转换回十进制数。

我的解决方案是

NumberComplement(num){
let bin= num.toString(2).split('').map( x => 1-x ).join('')
return parseInt(bin,2)
}

这个函数的时间复杂度是多少?为什么?

(让我困惑的部分是map函数,其中num已经从整数转换为由0和1组成的数组,我们知道数组的长度是log(num)+1,所以函数迭代 log(num)+1 次,这使得时间复杂度为 O(log(n))?........还是我想多了?只是 O(n)?

非常感谢您的宝贵时间!

【问题讨论】:

  • O(1) ....
  • @zerkms 为什么它是恒定的?我正在将 num 转换为数组并遍历整个数组.....
  • 它是每个splitmapjoin的53次迭代的上限
  • @zerkms 谢谢!我现在明白了……在谷歌搜索了 JS 中最大的精确整数值之后……

标签: javascript algorithm time-complexity


【解决方案1】:

让我们假设num 可以达到无穷大。然后,您将涉及这些函数调用:

| Function     | Asymptotic time complexity | Motivation                                                                                           |
|--------------|----------------------------|------------------------------------------------------------------------------------------------------|
| .toString(2) | O(log n)                   | Number of bits in num                                                                                |
| .split       | O(log n)                   | Number of characters from .toString, which is equal to number of bits in num                         |
| x => 1-x     | O(1)                       | x is either 0 or 1 so this does not vary with the size of n                                          |
| .map         | O(log n)                   | The anonymous function applied to each element in the result from .split: O(1) * O(log n) = O(log n) |
| .join        | O(log n)                   | Number of characters in the result from .map, which is equal to the number of bits in num            |
| .parseInt    | O(log n)                   | Number of characters in bin, which is equal to the number of bits in num                             |

把它们加起来:

.toString + .split + .map + .join + .parseInt =
O(log n) + O(log n) + O(log n) + O(log n) + O(log n) =
O(log n)

这在 Javascript 中是不正确的,然而,它的整数上限为 53 位。在 n 上设置上限时,您总是会得到 O(1) 的 Big-O 渐近时间复杂度。

【讨论】:

    猜你喜欢
    • 2020-12-03
    • 2017-09-11
    • 2011-08-07
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多