CodeGym /Adesua ahorow /Python SELF TW /不同難度等級的任務範例

不同難度等級的任務範例

Python SELF TW
等級 61 , 課堂 2
開放

3.1 常量複雜度的任務 O(1).

通過索引訪問數組元素:

通過索引訪問數組元素的操作是在常量時間內完成的,因為直接計算出元素的地址。


def get_element(arr, index):
    return arr[index]

在列表開頭插入元素(Deque):

使用雙端隊列 (deque) 可以在常量時間內將元素插入列表的開頭。


from collections import deque

def insert_element(dq, element):
    dq.appendleft(element)

3.2 線性複雜度的任務 O(n).

數組中的線性搜索:

在未排序的數組中搜索元素需要線性時間,因為可能需要檢查每個元素。


def linear_search(arr, target):
    for i in range(len(arr)):
        if arr[i] == target:
            return i
    return -1

計算數組中的元素數量:

遍歷數組中的所有元素以進行計數需要線性時間。


def count_elements(arr):
    count = 0
    for element in arr:
        count += 1
    return count

3.3 對數複雜度的任務 O(log n).

二分搜索:

使用二分搜索在排序數組中查找元素是在對數時間內完成的。


def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

在二叉搜索樹中插入元素:

在平衡二叉搜索樹 (BST) 中插入元素需要對數時間。


class Node:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.val = key
        
def insert(root, key):
    if root is None:
        return Node(key)
    if key < root.val:
        root.left = insert(root.left, key)
    else:
        root.right = insert(root.right, key)
    return root

3.4 二次複雜度的任務 O(n^2).

冒泡排序:

使用冒泡法排序數組是在二次時間內完成的。


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]

使用雙重循環檢查是否有重複:

使用雙重循環檢查數組中是否存在重複項需要二次時間。


def has_duplicates(arr):
    n = len(arr)
    for i in range(n):
        for j in range(i + 1, n):
            if arr[i] == arr[j]:
                return True
    return False

3.5 指數複雜度的任務 O(2^n).

河內塔問題:

解決河內塔問題需要指數時間,因為需要移動每個圓盤。


def hanoi(n, source, target, auxiliary):
    if n == 1:
        print(f"Move disk 1 from {source} to {target}")
        return
    hanoi(n - 1, source, auxiliary, target)
    print(f"Move disk {n} from {source} to {target}")
    hanoi(n - 1, auxiliary, target, source)

生成集合的所有子集:

生成集合的所有子集需要指數時間,因為每個子集都必須被考慮。


def generate_subsets(s):
    result = []
    subset = []

    def backtrack(index):
        if index == len(s):
            result.append(subset[:])
            return
        subset.append(s[index])
        backtrack(index + 1)
        subset.pop()
        backtrack(index + 1)
        
    backtrack(0)
    return result
        
print(generate_subsets([1, 2, 3]))
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION