Python面试题【数据结构和算法部分131-160】
Python面试题【数据结构和算法部分131-160】
- 问题:在Python中如何实现一个优先队列?
答案:
python
import heapq
class PriorityQueue:
def __init__(self):
self._queue = []
self._index = 0
def push(self, item, priority):
heapq.heappush(self._queue, (-priority, self._index, item))
self._index += 1
def pop(self):
return heapq.heappop(self._queue)[-1]
- 问题:如何在Python中实现一个循环数组?
答案:
python
class CircularArray:
def __init__(self, size):
self.array = [None] * size
self.size = size
self.head = 0
def get(self, index):
return self.array[(self.head + index) % self.size]
def set(self, index, value):
self.array[(self.head + index) % self.size] = value
def rotate(self, shift):
self.head = (self.head + shift) % self.size
- 问题:如何在Python中检查一个数是否是快乐数?
答案:
python
def is_happy(n):
seen = set()
while n != 1 and n not in seen:
seen.add(n)
n = sum(int(i)**2 for i in str(n))
return n == 1
- 问题:Python中如何实现计数排序?
答案:
python
def counting_sort(arr):
count = [0] * (max(arr) + 1)
for num in arr:
count[num] += 1
i = 0
for num, freq in enumerate(count):
for _ in range(freq):
arr[i] = num
i += 1
return arr
- 问题:如何在Python中找到所有可能的排列组合?
答案:
python
from itertools import permutations
def get_permutations(arr):
return list(permutations(arr))
- 问题:在Python中如何实现希尔排序?
答案:
python
def shell_sort(arr):
n = len(arr)
gap = n // 2
while gap > 0:
for i in range(gap, n):
temp = arr[i]
j = i
while j >= gap and arr[j - gap] > temp:
arr[j] = arr[j - gap]
j -= gap
arr[j] = temp
gap //= 2
return arr
-
问题:在Python中如何实现最小生成树算法?
答案:可以使用Kruskal或Prim算法实现最小生成树。这些算法通过选择边的方式来构造树,以确保树的权重总和最小,且不形成环。
-
问题:如何在Python中实现KMP字符串匹配算法?
答案:KMP算法通过计算一个"部分匹配"表来改善匹配过程,减少比较的次数。
-
问题:在Python中如何实现冒泡排序?
答案:
python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
- 问题:在Python中如何实现基数排序?
答案:
python
def radix_sort(arr):
RADIX = 10
placement = 1
max_digit = max(arr)
while placement < max_digit:
buckets = [[] for _ in range(RADIX)]
for i in arr:
tmp = int((i / placement) % RADIX)
buckets[tmp].append(i)
a = 0
for b in range(RADIX):
buck = buckets[b]
for i in buck:
arr[a] = i
a += 1
placement *= RADIX
return arr
- 问题:如何在Python中实现深度优先搜索(DFS)用于图的遍历?
答案:
python
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
for next in graph[start] - visited:
dfs(graph, next, visited)
return visited
- 问题:在Python中如何使用广度优先搜索(BFS)找到图中从起点到终点的最短路径?
答案:
python
from collections import deque
def bfs_shortest_path(graph, start, goal):
explored = set()
queue = deque([(start, [start])])
while queue:
current, path = queue.popleft()
if current == goal:
return path
for next in graph[current]:
if next not in explored:
explored.add(next)
queue.append((next, path + [next]))
return None
- 问题:如何在Python中检测有向图中的环?
答案:
python
def detect_cycle(graph):
WHITE, GRAY, BLACK = 0, 1, 2
color = {u: WHITE for u in graph}
def dfs(node):
if color[node] == GRAY:
return True
if color[node] == BLACK:
return False
color[node] = GRAY
for neighbour in graph[node]:
if dfs(neighbour):
return True
color[node] = BLACK
return False
for node in graph:
if color[node] == WHITE:
if dfs(node):
return True
return False
- 问题:如何在Python中实现Floyd-Warshall算法?
答案:
python
def floyd_warshall(weights):
V = len(weights)
dist = list(map(lambda i: list(map(lambda j: j, i)), weights))
for k in range(V):
for i in range(V):
for j in range(V):
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
return dist
- 问题:如何在Python中实现Dijkstra算法?
答案:
python
import heapq
def dijkstra(graph, start):
min_dist = {vertex: float('infinity') for vertex in graph}
min_dist[start] = 0
pq = [(0, start)]
while pq:
current_dist, current_vertex = heapq.heappop(pq)
if current_dist > min_dist[current_vertex]:
continue
for neighbor, weight in graph[current_vertex].items():
distance = current_dist + weight
if distance < min_dist[neighbor]:
min_dist[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return min_dist
- 问题:如何在Python中找出数组中的第k个最大元素?
答案:
python
import heapq
def findKthLargest(nums, k):
return heapq.nlargest(k, nums)[-1]
- 问题:在Python中如何实现并查集?
答案:
python
class UnionFind:
def __init__(self, size):
self.root = [i for i in range(size)]
def find(self, x):
while x != self.root[x]:
x = self.root[x]
return x
def union(self, x, y):
rootX = self.find(x)
rootY = self.find(y)
if rootX != rootY:
self.root[rootY] = rootX
def connected(self, x, y):
return self.find(x) == self.find(y)
- 问题:如何在Python中实现二叉搜索树的插入操作?
答案:
python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insert_into_bst(root, val):
if not root:
return TreeNode(val)
if val < root.val:
root.left = insert_into_bst(root.left, val)
else:
root.right = insert_into_bst(root.right, val)
return root
- 问题:如何在Python中实现二叉树的后序遍历?
答案:
python
def postorder_traversal(root):
result = []
if root:
result += postorder_traversal(root.left)
result += postorder_traversal(root.right)
result.append(root.val)
return result
- 问题:如何在Python中找到未排序数组中的最长连续序列?
答案:
python
def longest_consecutive(nums):
num_set = set(nums)
longest = 0
for num in num_set:
if num - 1 not in num_set:
current_num = num
current_streak = 1
while current_num + 1 in num_set:
current_num += 1
current_streak += 1
longest = max(longest, current_streak)
return longest
- 问题:在Python中如何实现线性查找?
答案:
python
def linear_search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
- 问题:如何在Python中实现插入排序算法?
答案:
python
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
- 问题:在Python中如何实现选择排序算法?
答案:
python
def selection_sort(arr):
for i in range(len(arr)):
min_idx = i
for j in range(i+1, len(arr)):
if arr[min_idx] > arr[j]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
- 问题:如何在Python中找到数组中的峰值元素?
答案:
python
def find_peak_element(nums):
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) // 2
if nums[mid] > nums[mid + 1]:
right = mid
else:
left = mid + 1
return left
- 问题:在Python中如何实现桶排序算法?
答案:
python
def bucket_sort(arr):
max_value = max(arr)
size = max_value // len(arr)
buckets = [[] for _ in range(size)]
for i in range(len(arr)):
j = arr[i] // size
if j != size:
buckets[j].append(arr[i])
else:
buckets[size - 1].append(arr[i])
for i in range(size):
insertion_sort(buckets[i])
result = []
for i in range(size):
result = result + buckets[i]
return result
- 问题:如何在Python中实现计算一个数的幂?
答案:
python
def power(x, n):
if n == 0:
return 1
elif n % 2 == 0:
return power(x, n // 2) ** 2
else:
return x * power(x, n // 2) ** 2
- 问题:在Python中如何在一个包含从0到n的整数的数组中找到缺失的数字?
答案:
python
def missing_number(nums):
n = len(nums)
expected_sum = n * (n + 1) // 2
actual_sum = sum(nums)
return expected_sum - actual_sum
- 问题:在Python中如何实现二叉树的前序遍历?
答案:
python
def preorder_traversal(root):
result = []
if root:
result.append(root.val)
result += preorder_traversal(root.left)
result += preorder_traversal(root.right)
return result
- 问题:如何在Python中实现一个简单的散列表?
答案:
python
class HashTable:
def __init__(self, size):
self.size = size
self.table = [None] * size
def hash_function(self, key):
return key % self.size
def insert(self, key, value):
hash_index = self.hash_function(key)
self.table[hash_index] = value
def get(self, key):
hash_index = self.hash_function(key)
return self.table[hash_index]
- 问题:在Python中如何找到第n个斐波那契数?
答案:
python
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a