赞
踩
// 时间复杂度 function getTime(n) { let sum = 0 // 执行1次 for (let i = 1; i < n; i++) { // 执行n次 let i 执行一次 sum += i // 执行n次 } return sum } // 时间复杂度为 O(2n + 2) 因为系数、常熟对 n 的增长规模没有影响 不需要考虑,可以忽略 // 所以时间复杂度为 O(n) // 如果一段代码中没有循环、递归等语句,通常时间复杂度都是O(1) function getTime(n) { let i = 1; while (i <= n) { // 执行 n / 10 次 i = i * 10; } } // 这种成倍数的就是O(logn) function getTime(n) { let sum = 0; // 执行1次 for (let i = 1; i <= n; i++) { // 执行 n 次,let i 执行1次 for (let j = 1; j <= n; j++) { // 执行n * n 次 sum += i * j; } } return sum; } // 类似这种嵌套2层的for循环 一般都会选择执行次数最多的 时间复杂度就是 O(n^2) // 常见的时间复杂度(从低到高): O(1) O(logn) O(n) O(nlogn) O(n^2) // 空间复杂度 // 常见的空间复杂度 // O(1) let a = 1; let b = 1 // O(n) let arr = new Array(n) // O(n^2) let arr = [] for (let a = 0; a < n; a++) { arr[a] = a for (let b = 0; b < n; b++) { arr[a][b] = b } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。