求时间复杂度O(n)

时间:2019-04-24 15:01:51

标签: python time-complexity

考虑以下代码:

library(shiny)

ui <- fluidPage(titlePanel("NFL Combine players"), selectInput(inputId = "num", 
label = "Choose a Stat", choices = c("1", "Wt", "Vertical", "forty", "BenchReps", 
"Cone", "BroadJump", "Shuttle")),

           selectInput(inputId = "pos", label = "Player Positions", selected = 5,
                       choices = c("1", "CB", "DB", "DE", "DT", "EDGE", "FB", "FS", "G", "ILB", "K", "LB", "LS", "NT", "OG", "OL", "OLB", "OT", "P", "QB", "RB", "S", "SS", "TE", "WR")),
           plotOutput("hist", click = "plot_click")
)

server <- function(input, output) {
    output$hist = renderPlot({
        hist(rnorm(as.numeric(input$num), as.numeric(input$pos)))
    })
}

# Run the application
shinyApp(ui = ui, server = server)

我试图弄清楚递归的时间复杂度是多少 函数import matplotlib.pyplot as plt # Returns 2^n def pow(n): if n == 0: return 1 x = pow(n//2) if n%2 == 0: return x*x return 2*x*x y = [10^4, 10^5,10^6, 10^7, 10^8, 10^9, 10^10] z = [] for n in y: start = time.time() pow(n) print(n, time.time() - start) # elapsed time z.append(time.time()-start) plt.plot(y,z) plt.show()

我将时间复杂度计算为pow(n),但是使用函数时 O(log(n))函数似乎是线性的。怎么会来?

为什么时间复杂度为time.time()而不是O(n)

Graph

1 个答案:

答案 0 :(得分:1)

如果将示例中x*x的所有外观替换为常量(例如1)或将其乘以加法,您将发现确实确实O(log(n))复杂,因为您的函数被调用log(n)次(尽管在这种情况下,我们测量的时间确实很小,所以在这种情况下使用time的结果可能无法反映该函数的复杂性)。我认为结论是您对乘法为O(1)的假设是不正确的(例如参见this question),尤其是因为您乘法的数字确实很大,已经不再适合传统的32 / 64位表示。