什么是复杂度

image.png
image.png

时间复杂度-程序执行时需要的计算量(CPU)

image.png
image.png

空间复杂度-程序执行时需要的内存空间

image.png

将一个数组旋转K步

image.png

  1. function rotate1(arr, k) {
  2. const length = arr.length
  3. if (!k || length === 0) return arr
  4. const step = Math.abs(k % length) // abs 取绝对值
  5. for (let i = 0; i < step; i++) {
  6. const n = arr.pop()
  7. if (n != null) {
  8. arr.unshift(n) //数组是一个有序结构,unshift操作非常慢 O(n)
  9. }
  10. }
  11. return arr
  12. }
  13. function rotate2(arr, k) {
  14. const length = arr.length
  15. if (!k || length === 0) return arr
  16. const step = Math.abs(k % length) // abs 取绝对值
  17. const part1 = arr.slice(-step) // O(1)
  18. const part2 = arr.slice(0, length - step)
  19. const part3 = part1.concat(part2)
  20. return part3
  21. }
  22. // 功能测试
  23. // const arr = [1, 2, 3, 4, 5, 6, 7]
  24. // const arr1 = rotate2(arr, 3)
  25. // console.info(arr1);
  26. // 性能测试
  27. const arr1 = []
  28. for (let i = 1; i < 10 * 10000; i++) {
  29. arr1.push(i)
  30. }
  31. console.time('rotate1')
  32. rotate1(arr1, 9 * 1000)
  33. console.timeEnd('rotate1') //152.12ms O(n^2)
  34. const arr2 = []
  35. for (let i = 1; i < 10 * 10000; i++) {
  36. arr2.push(i)
  37. }
  38. console.time('rotate2')
  39. rotate2(arr2, 9 * 1000)
  40. console.timeEnd('rotate2') //0.41ms O(1)

image.png

判断字符串是否括号匹配

image.png

image.png

  1. /*
  2. *
  3. *判断是否括号匹配
  4. */
  5. // 判断左右括号是否匹配
  6. function isMatch(left, right) {
  7. if (left === "{" && right === "}") return true
  8. if (left === "[" && right === "]") return true
  9. if (left === "(" && right === ")") return true
  10. return false
  11. }
  12. function matchBracket(str) {
  13. const length = str.length
  14. if (length === 0) return true
  15. const stack = []
  16. const leftSymbols = '{[('
  17. const rightSymbols = ')]}'
  18. for (let i = 0; i < length; i++) {
  19. const s = str[i]
  20. if (leftSymbols.includes(s)) {
  21. //左括号,压栈
  22. stack.push(s)
  23. } else if (rightSymbols.includes(s)) {
  24. //右括号,判断栈顶(是否出栈)
  25. const top = stack[stack.length - 1]
  26. if (isMatch(top, s)) {
  27. stack.pop()
  28. } else {
  29. return false
  30. }
  31. }
  32. }
  33. return stack.length === 0
  34. }
  35. // 功能测试
  36. const str = '{a[d((s)c]d}a'
  37. console.info(123, matchBracket(str))

时间复杂度:O(n)
空间复杂度:O(n)

image.png
image.png
image.png