GitHub (opens new window)

数据结构与算法

coderljw 2024-10-13 数据结构与算法
  • 数据结构与算法
  • 斐波那契数列
  • 排序算法
  • 二分法查找
  • 树形数据结构化
大约 5 分钟

# 1. 中点

# 2. 异或运算 ^

# 3. master 公式

  1. log(b, a) > d 复杂度为 O(Nlog(b,a))O(N^{log(b, a)})
  2. log(b, a) = d 复杂度为 O(NdlogN)O(N^{d} * logN)
  3. log(b, a) < d 复杂度为 O(Nd)O(N^{d})

# 4.斐波那契数列

# 5. 排序算法

# 6. 二分法查找

function binarySearch(ary, target) {
  let L = 0
  let R = ary.length

  while (L <= R) {
    let mid = L + ((R - L) >> 1)
    if (target === ary[mid]) return mid
    else if (target < ary[mid]) R = mid - 1
    else L = mid + 1
  }

  return -1
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 7. 树形数据结构化

const ary = [
  {
    id: 1,
    pid: 0,
    title: 'jack',
  },
  {
    id: 2,
    pid: 0,
    title: 'pony',
  },
  {
    id: 3,
    pid: 1,
    title: 'Evan You',
  },
  {
    id: 4,
    pid: 3,
    title: 'coderljw',
  },
]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function formatDataTree(ary) {
  const parents = ary.filter(p => p.pid === 0)
  const children = ary.filter(c => c.pid !== 0)

  aryToTree(parents, children)
  return parents

  function aryToTree(parents, children) {
    parents.map(p => {
      children.forEach((c, i) => {
        if (p.id === c.pid) {
          if (p.children) p.children.push(c)
          else p.children = [c]
          aryToTree(p.children, children)
        }
      })
    })
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const tree = ary.filter(p => {
  const children = ary.filter(c => p.id === c.pid)
  children.length && (p.children = children)
  return p.pid === 0
})
1
2
3
4
5
以父之名
周杰伦.mp3