📜  数据结构和算法 |设置 9(1)

📅  最后修改于: 2023-12-03 15:26:09.663000             🧑  作者: Mango

#### 数据结构和算法 | 设置 9

##### 数据结构

###### 数组

``````# 创建一个整数类型的数组，包含5个元素
arr = [0] * 5
``````
###### 链表

``````class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next

# 创建一个包含1, 2, 3的链表
``````
###### 栈

``````class Stack:
def __init__(self):
self.stack = []

def push(self, x):
self.stack.append(x)

def pop(self):
if not self.empty():
return self.stack.pop()

def peak(self):
if not self.empty():
return self.stack[-1]

def empty(self):
return len(self.stack) == 0
``````
###### 队列

``````class Queue:
def __init__(self):
self.queue = []

def push(self, x):
self.queue.append(x)

def pop(self):
if not self.empty():
return self.queue.pop(0)

def front(self):
if not self.empty():
return self.queue[0]

def empty(self):
return len(self.queue) == 0
``````
##### 算法

###### 排序

``````def quick_sort(arr):
if len(arr) <= 1:
return arr

pivot = arr[0]
left = [x for x in arr[1:] if x < pivot]
right = [x for x in arr[1:] if x >= pivot]

return quick_sort(left) + [pivot] + quick_sort(right)
``````
###### 查找

``````def binary_search(arr, target):
low, high = 0, len(arr) - 1

while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1

return -1
``````
###### 动态规划

``````def knapsack(capacity, weights, values):
n = len(weights)
dp = [0] * (capacity + 1)

for i in range(n):
for j in range(capacity, weights[i] - 1, -1):
dp[j] = max(dp[j], dp[j - weights[i]] + values[i])

return dp[capacity]
``````