002-Data Structures

89 阅读1分钟

Data Structures Interfaces:

  • collection of supported operations is called interface( also API)
  • two main interfaces:
    • Sequence and Set

Sequence Interface:

  • Maintain a sequence of items (order is extrinsic)
  • Special case interfaces:
    • stack
    • queue

Set Interface:

  • Maintain a set of items having unique keys
  • intrinsic order
  • Special case : dictionary

Sequence about extrinsic order , Set is about intrinsic order

  • 序列是一种有序的数据结构,其中元素按照一定的外部顺序排列。这意味着序列中的每个元素都有一个明确的位置(索引),并且可以按照特定的顺序进行访问和操作

  • 集合是一种无序的数据结构,其中元素没有明确的顺序排列。集合中的元素是独立的,没有特定的顺序要求。

  • 集合数据结构强调元素的唯一性和无序性,主要用于*去重或判断元素是否存在,而不强调元素之间的顺序关系。

Array Sequence:

  • Array is great for static operations ,but not at dynamic operations
  • Inserting and removing requires:
    • reallocating the array
    • shifting all items after modefied item

Linkd List Sequence:

  • Pointer data structure
  • Each item stored in a node which contains a pointer to the next node in sequence
  • Each node has two fields;
    • node.item
    • node.next
  • manipulate nodes by relinking pointers
  • Maintain pointers to the first node in sequence(called head)
  • insert and delete in θ(1)\theta(1) time
  • But get_at (i) and set_at (i,x) take O(n)O(n) time

Dynamic Array Sequence

  • python "list" is a dynamic array
  • To avoid reallocating , allocate extra space

Amortized analysis :

中译:摊销分析
对算法的时间复杂度进行分析,进而评估一个算法的平均性能,而不是单次操作上的性能,通常用于动态数据结构或算法中。

Dynamic Array deletion:

动态数组中,插入和删除元素的时间复杂度为O(1)O(1),但动态数组的空间利用方面存在浪费(因为在动态调整大小时,需要额外的空间)
当数组的使用率小于 rd 时(rd为一个较小的比例,如1/4),将数组的大小调整为一个更合适的比例 ri(ri > rd,如1/2),这种方式可以限制额外空间的使用量
rd=11+ε,ri=rd+12=2+ε1+ε r_d={\frac{1}{1+{\varepsilon}}},r_i={\frac{r_d+1}{2}}=\frac{2+{\varepsilon}}{1+{\varepsilon}},
rird=1+0.5ε\frac{r_i}{r_d}=1+0.5\varepsilon, 即额外空间使用量可以控制在 (1 + ε)n 的范围内