数据结构篇一:Array, Linked List, Stack

2021-12-03  本文已影响0人  walkerwzy

这是一位 google 工程师分享的8小时的数据结构的视频,我的笔记

前几个比较基础,只记录了些关键字和提纲

Static and Dynamic Arrays

static array

usage:

operation complexity:
access: O(1)
search: O(n)
insert: O(n)
append: O(1)
delet: O(n)
需要遍历的操作就是O(n)

Q: How to implement a dynamic array?
A:

  1. static array with an initial capacity
  2. add new elements, keep tracking the size
  3. if exceed capacity, create a new static array with twice the capacity
    • and copy the original elements into it

Singly and Doubly Linked Lists

单向/双向链表

sequential list of nodes that hold data which point to other nodes also containing data.

usage:

上述两上问号后续在Hash Table一节里自然就解惑了

Terminology
Head / Tail / Pointer / Node

Singly vs Doubly

insertion

removal

singly需要两个游标:

doubly却只需要一个:

Complexity
searth: O(n)
insert at head/tail: O(1)
remove at head: O(1)
remove at tail: O(n) (singly) / O(1) (doubly)
因为即使我们知道tail在哪,在单向链表中,我们也找不到它的前一个去设置为新的tail
remove in middle: O(n)

Stack

Usage

Complexity
push/pop/peek/size: O(1)
search: O(n)

双向链表实现一个Stack,基本上就是操作tail

Queues

Usage

Complexity

只有contains, revomval需要遍历,其它操作(出入列等)都是O(1)

实现一个BFS:

基本就是动态往 queue 里添加子节点,当前级别元素访问完后, 再 dequeue 出来的就是所有的下一级子节点


image.png

双向列表实现Queue,入列用tail,出列用head,即添加的总在尾巴,永远从头部取出。

上一篇 下一篇

猜你喜欢

热点阅读