CSE12 ucsd
·** Data structure**
Record:把描述同一个东西的不同属性放在一起
Array:靠index找数据
Linked List :node 靠pointer一个一个连过去 ---- avoids shifting problem
Binary tree:每个node最多2个children
Hash Table:我有一个规则,可以快速决定数据应该放在哪个位置(它有一个hash function)(如果不同数据得出同一个index,那就引入linked list)
Heap:本身是一种特殊的tree(max heap:parent>children)
Graph: vertices + edges (tree 是一种特殊的graph)
· Algorithms
A computational problem specifies the problem input, a question to be answered, and the desired output.
NP-complete problems are a set of problems for which no known efficient algorithm exists.
An algorithm with a polynomial runtime is considered efficient.只要不是指数型增长
· Relation between data structure and algorithms
The algorithm to append an item to a linked list points the tail node's next pointer and the list's tail pointer to the new node
ArrayList
ArrayList can directly access an element by index.
size:列表中实际有多少个元素。
capacity:底层数组能容纳多少个元素,即 data.length。
有效元素位于下标 0 到 size - 1。
set 是替换,add 是插入
在中间插入,需要把后面的元素向右移,for (int i = size; i > index; i--) {
data[i] = data[i - 1]; (就是右边=左边)
}
删除时,后面的元素向左移,for (int i = index; i < size - 1; i++) {
data[i] = data[i + 1]; (就是左边=右边)
}
Linked Lists
linked list最前面添加数字
https://img2024.cnblogs.com/blog/3659684/202609/3659684-20260930061005393-208139473.png
linked list最后面添加数字

linked list返回某数字

linked list删除第一个数字(移动head以后会自动删掉第一个)

linked list删除中间数字(第二个指向第四个)
current.next = current.next.next;
完整版
public void remove(int value) {
if (head == null) {
return;
}
if (head.data == value) {
head = head.next;
return;
}
Node current = head;
while (current.next != null) {
if (current.next.data == value) {
current.next = current.next.next;
return;
}
current = current.next;
}
}
· Abstract data types
抽象数据类型,规定能做什么,但不规定具体怎么做
其实就是ADT是想一个东西可以干嘛(需要什么功能),data structure(implementation)是具体代码怎么写(比如语法啦......)
https://img2024.cnblogs.com/blog/3659684/202610/3659684-20261001090959134-2669221.png
· Linked list

Linked List search

主要方法:item就是adt,node就是data structure

Singly-linked list remove-node-after operation删除的是curNode后面的node
如果说curNode就是tail,那直接false,返回原Linked List
ListTraverseReverse(list)
ListTraverse(list)
ListTraverse() can be used to traverse a doubly-linked list.
ListTraverseReverse() cannot be used to traverse a singly-linked list.
add:是右往左遍历
remove:左往右遍历
Iterator
next():返回右边的元素,再向右移动,canRemove = true; forward = true;
previous():返回左边的元素,再向左移动 ,canRemove = true; forward = false;
forward:最近一次成功移动的方向,用来确定目标节点,最近一次右移是true;最近一次左移是false;
canRemove:现在有没有资格调用 remove() 去删除 next() 或 previous() 返回的元素
set/remove()都是删除/修改最近一次m储存的元素
it.add(value) 在游标所在的位置插入元素,插入后游标位于新元素后面。
it.previous() 返回游标左边那个元素,然后把游标向左移动一格
Map abstract data type
Iteration order is not defined by the map ADT itself, but rather is implementation-dependent.


Hash tables
Hash Table(哈希表 / 散列表)是一种 Data Structure(数据结构),用来快速存储、查找和删除数据。
它最大的特点是:不需要一个一个找,就能通过 key(键)快速找到对应的 value(值)。
Hash Function:一个函数,把 Key 转换成一个数字(Hash Code)。
Hash Table 底层使用一个 Array,每个位置叫作一个 Bucket(桶)。
从hash code变成bucket index
A hash map's length is the number of items.
Collision:两个不同的 Key 得到了相同的 index
Chaining is a collision resolution technique where each bucket has a list of items (so bucket 6's list could have keys 86 and 16)
Open addressing is a collision resolution technique where collisions are resolved by looking for an empty bucket elsewhere in the table
Mid-square hash function
Mid-square 的 Base 2 implementation:

Chaining allows a hash table to store two or more distinct keys with the same hash code.
HashInsert(hashTable, key, value) {
// 1. 根据 key 计算它应该进入哪个 Bucket
bucketIndex = Hash(key) % hashTable->length;
// 2. currentItem 指向这个 Bucket 的第一个 Node
currentItem = hashTable[bucketIndex];
// previousItem 初始为 null,因为还没开始遍历
previousItem = null;
// 3. 遍历 Bucket 里的 LinkedList
// 只要 currentItem 不是 null,就继续查找
while (currentItem != null) {
// 检查当前 Node 的 key 是否等于要插入的 key
if (key == currentItem->key) {
// 如果 key 已经存在,直接更新它的 value
currentItem->value = value;
// 更新成功,直接结束整个方法
return true;
}
// 如果 key 不相同,继续往后找
// previousItem 记录当前 Node
previousItem = currentItem;
// currentItem 移动到下一个 Node
currentItem = currentItem->next;
}
// 4. 如果 while 正常结束,说明没有找到相同的 key
// 因此需要创建一个新的 Node
newItem = Allocate new chaining hash table item;
// 设置新 Node 的 key 和 value
newItem->key = key;
newItem->value = value;
// 新 Node 将放在链表末尾,所以 next = null
newItem->next = null;
// 5. 把新 Node 插入 LinkedList
// 情况 A:Bucket 原本是空的
if (hashTable[bucketIndex] == null) {
// 让 Bucket 直接指向新 Node
// 新 Node 成为 LinkedList 的第一个 Node
hashTable[bucketIndex] = newItem;
}
// 情况 B:Bucket 原本不是空的
else {
// 此时 previousItem 指向最后一个 Node
// 把新 Node 接到最后
previousItem->next = newItem;
}
// 6. 插入成功
return true;
}
HashRemove(hashTable, key) {
// 1. 根据 key 计算 Bucket Index
bucketIndex = Hash(key) % hashTable->length;
// 2. currentItem 指向 Bucket 的第一个 Node
currentItem = hashTable[bucketIndex];
// previousItem 初始为 null
// 因为第一个 Node 前面没有 Node
previousItem = null;
// 3. 遍历 LinkedList
// 只要 currentItem 不是 null,就继续查找
while (currentItem != null) {
// 检查当前 Node 是否是要删除的 Node
if (key == currentItem->key) {
// 情况 A:previousItem 是 null
// 说明 currentItem 是第一个 Node
if (previousItem == null) {
// 让 Bucket 指向第二个 Node
// 相当于删除原来的第一个 Node
hashTable[bucketIndex] = currentItem->next;
}
// 情况 B:previousItem 不是 null
// 说明 currentItem 不是第一个 Node
else {
// 让前一个 Node 直接指向后一个 Node
// 跳过 currentItem,实现删除
previousItem->next = currentItem->next;
}
// 找到并删除成功,结束整个方法
return true;
}
// 4. 如果当前 Node 不是要删除的
// 就继续往后遍历
// previousItem 记录当前 Node
previousItem = currentItem;
// currentItem 移动到下一个 Node
currentItem = currentItem->next;
}
// 5. 如果 while 正常结束
// 说明没有找到目标 key
// 因此删除失败
return false;
}
linear probing handles a collision by starting at the key's mapped bucket, and then linearly searches subsequent buckets until an empty bucket is found
Empty-since-start:从 Hash Table 创建开始,这个 Bucket 就从来没存过东西。从来没人用过,可以停止 Search。
Empty-after-removal:这个 Bucket 以前存过东西,但是后来被删除了。以前有人用过,后面可能还有数据,必须继续 Search。
Midterm






Stack Abstract Data Type(栈抽象数据类型)
(就像个瓶子)
A stack is referred to as a last-in first-out (LIFO),can both be array-based stacks and linkedlist-based stacks
common stack ADT operations

push添加,pop删除并返回
linkedlist-based stacks
A push operation changes the stack's top node pointer
array-based
The stack's bottom item is at array[0], and the top item is at array[length - 1]
unbounded stack
bounded stack
allocationSize:Stack 底层数组容量
length:Stack 当前元素数量(!!!和以前的不一样)
maxLength:Bounded Stack 允许的最大元素数量
DBS(Deep Breath Search)就是一种遍历 Graph 的算法
Queue Abstract Data Type(队列抽象数据类型)
Queue(队列) 是一种 ADT(抽象数据类型),表示一个元素集合,其中元素只能从队列的末尾(end)插入,从队列的前端(front)删除。
Enqueue(入队):将一个元素插入 Queue 的末尾。
Dequeue(出队):删除并返回 Queue 最前面的元素



·Linkedlist-based queue
·Array-based queue
allocationSize: Array 的总容量(Capacity)
length: 元素个数
frontIndex:Queue 最前面元素所在的 Array Index
Queue 的内容从 array[frontIndex] 开始,向后连续存储 length 个元素。
如果到达 Array 的末尾,但 Queue 还有其他元素,那么剩余元素会从 array[0] 开始存储。
这叫做 Circular Queue(循环队列)。
·Bounded vs. Unbounded Queue
基于数组的 Queue 可以通过 maxLength 同时支持 Bounded 和 Unbounded Queue:
- maxLength < 0:Unbounded Queue(无界队列)。
- maxLength >= 0:Bounded Queue(有界队列)。
Resize(扩容)操作:
- 创建一个更大的 Array,通常将原来的 allocationSize 翻倍。
- 如果 maxLength 非负,新容量不能超过 maxLength,因此取两者的最小值。
- 将旧 Array 中的有效元素按照 Queue 的顺序复制到新 Array。
4. 将 frontIndex 重置为 0。

·Enqueue and dequeue operations
enqueue item计算公式:(frontIndex + length) % allocationSize
·BFS(Breath First Search)
BFS 就是从一个起点开始,一层一层地遍历 Graph,直到访问完所有能够到达的 Vertex。
它使用两个数据结构:
- frontierQueue(Queue):存放已经发现、但还没访问的 Vertex。
- discoveredSet(Set):记录所有已经发现的 Vertex,防止重复加入 Queue。
Heap
不需要把所有元素排序,只需要能够快速找到和删除最大元素。
A max-heap is a complete binary tree in which each node's key is greater than or equal to its children's keys.
A customer with a higher priority has a lower numerical value in the min-heap.
Priority Queue 则是:Priority 高的元素先出去,不一定按照进入顺序。
Enqueue(插入):把新的 item 加入 Priority Queue,并按优先级确定它的逻辑位置。
Dequeue(删除并返回):删除并返回 Front(最高优先级)的 item。
新加入的 item 要排在所有优先级相同或更高的 item 后面
Binary Tree & BST
Full:每个 Node 有 0 或 2 个 Children。
Complete:除了最后一层全部填满,最后一层从左往右排列。
Perfect:所有层全部填满。
BSP:利用 Binary Tree 不断划分空间。
BST:Left Subtree < Root < Right Subtree。
Search:从 Root 开始,根据 Key 大小往 Left 或 Right。
Insert:找到 null Child 位置插入新 Node。
Remove 0 Children:直接删除。
Remove 1 Child:唯一 Child 接替。
Remove 2 Children:找到 Successor,复制 Key,再删除原 Successor。
Successor:下一个更大的 Key。
Predecessor:上一个更小的 Key。
Inorder:Left → Root → Right。
Reverse Inorder:Right → Root → Left。
Preorder:Root → Left → Right。
Postorder:Left → Right → Root。
Visitor Function:决定访问 Node 时执行的操作。
Search / Insert / Remove:Balanced O(log N),Worst O(N)。
Traversal:O(N)。
Perfect BST:N = 2^(h+1) - 1。
Worst-case Search Comparisons:h + 1。
Search:
Balanced:O(log N)
Worst Unbalanced:O(N)
Iterative Auxiliary Space:O(1)
Insert:
Balanced:O(log N)
Worst Unbalanced:O(N)
Iterative Auxiliary Space:O(1)
Remove:
Balanced:O(log N)
Worst Unbalanced:O(N)
Iterative Auxiliary Space:O(1)
Traversal:
Time:O(N)
Recursive Auxiliary Space:O(h+1)
其中:
N = Number of Nodes
h = Height,按照 Edges 计算。
Balanced BST 的 Height 是 O(log N)。
最坏情况下 Unbalanced BST 的 Height 是 O(N)。
Search、Insert、Remove 的时间复杂度取决于 Tree Height。
Traversal 需要访问全部 N 个 Nodes,因此为 O(N)。
期末复习
· Java Review
├── Generics 泛型
│ ├── Generic Class
│ ├── Generic Method
│ ├── Comparable
│ └── Type Erasure
├── Shallow Copy / Deep Copy
├── Data Abstraction
│ ├── ADT
│ ├── API
│ └── Backend Data Structure
├── Java Collections
│ ├── Interface
│ ├── Abstract Class
│ └── Concrete Class
├── Exceptions
│ ├── Checked / Unchecked
│ └── try / catch / throw / throws
└── Testing
├── Black Box / White Box
├── JUnit
└── Assertion
· ArrayList
├── Backend: Array
├── Size vs. Capacity
├── expandCapacity()
├── Basic Operations
│ ├── add / append
│ ├── get / set
│ ├── remove
│ └── find
├── Shifting Elements
├── Runtime Analysis
└── Application
└── Prefix Sum
· LinkedList
├── Types
│ ├── Singly Linked List
│ ├── Doubly Linked List
│ └── Circular Linked List
├── Structure
│ ├── Node
│ ├── Head / Tail
│ ├── Next / Prev
│ └── Dummy / Sentinel Node
├── Basic Operations
│ ├── add
│ ├── remove
│ ├── get / set
│ └── search
└── Iterator
├── Iterator / ListIterator
├── left / right / index
├── canRemove / forward
├── hasNext / next
├── hasPrevious / previous
└── add / remove / set
· Runtime Analysis
├── Benchmark
├── Asymptotic Analysis
├── Big-O Notation
├── Best Case
├── Average Case
├── Worst Case
├── Amortized Runtime
└── Code Analysis
├── Single Loop
├── Nested Loop
├── Consecutive Loops
├── Early Return
└── Recursive Methods
· Hashing
├── Hash Table
├── Hash Code
├── Hash Function
│ ├── Division Method
│ └── Mid-Square Method
├── Collision
│ ├── Separate Chaining
│ └── Linear Probing
│ ├── Empty Since Start
│ └── Empty After Removal
├── Load Factor
├── Rehashing / Expand Capacity
├── HashMap
│ ├── Key / Value
│ └── put / get / remove
├── HashSet
│ └── Unique Elements
└── Runtime Analysis
· Stack / Queue / Deque
├── Deque
│ ├── Circular Array
│ ├── Front / Rear / Size
│ ├── Wraparound
│ ├── addFirst / addLast
│ ├── removeFirst / removeLast
│ └── expandCapacity
├── Stack
│ ├── LIFO
│ ├── push / pop / peek
│ ├── Valid Brackets
│ └── Expression Evaluation
├── Queue
│ ├── FIFO
│ └── enqueue / dequeue / peek
└── Applications
├── DFS (Stack)
├── BFS (Queue)
├── Maze
├── Visited
└── Path Reconstruction
· Priority Queue & Heap
├── Priority Queue (ADT)
├── Heap (Data Structure)
│ ├── Min Heap
│ └── Max Heap
├── Complete Binary Tree
├── Heap Property
├── Array Implementation
│ ├── 0-based Index
│ ├── 1-based Index
│ ├── Parent Index
│ ├── Left Child Index
│ └── Right Child Index
├── Basic Operations
│ ├── insert
│ ├── remove
│ └── peek
├── Percolate Up / Bubble Up
├── Percolate Down
├── Heapify
└── Runtime Analysis
· Tree
├── Basic Terminology
│ ├── Root
│ ├── Parent / Child
│ ├── Leaf / Internal Node
│ ├── Depth / Height
│ └── Subtree
├── Types of Trees
│ ├── Binary Tree
│ ├── Full Binary Tree
│ ├── Complete Binary Tree
│ └── Balanced Binary Tree
├── Tree Traversal
│ ├── Preorder
│ ├── Inorder
│ ├── Postorder
│ └── Level Order
└── Binary Search Tree (BST)
├── BST Property
├── insert / search / remove
├── Recursive / Iterative
├── Minimum / Maximum
├── Successor
├── Removal Cases
│ ├── No Child
│ ├── One Child
│ └── Two Children
├── Clone / Copy
├── Lower Bound / Upper Bound
├── Floor
├── Balanced BST
├── TreeSet / TreeMap
└── Application: Concert Tickets
· Sorting
├── Comparison-Based Sorting
│ ├── Bubble Sort
│ ├── Selection Sort
│ ├── Insertion Sort
│ ├── Tree Sort
│ ├── Heap Sort
│ ├── Merge Sort
│ └── Quick Sort
├── Non-Comparison-Based Sorting
│ ├── Counting Sort
│ └── Radix Sort
└── Analysis
├── Best / Worst Case Runtime
├── Space Complexity
├── Stability
└── In-place Sorting

浙公网安备 33010602011771号