返回

数据结构与算法学习记录分享

前端

踏上数据结构与算法的学习之旅,犹如开启一场精彩的探索之旅。在这一路上,我记录下了宝贵的学习经验,从中汲取智慧,不断精进。

数组

数组是数据结构的基础,它以有序的方式存储元素。在 LeetCode 1 题中,我们需要找出两个数之和为目标值的数组下标。利用双指针技术,我们可以高效解决此问题。

def twoSum(nums, target):
    left, right = 0, len(nums) - 1
    while left < right:
        if nums[left] + nums[right] == target:
            return [left, right]
        elif nums[left] + nums[right] < target:
            left += 1
        else:
            right -= 1
    return None

链表

链表是一种动态数据结构,它通过指针将元素连接起来。在 LeetCode 2 题中,我们要求反转一个链表。利用迭代法,我们可以逐个反转节点指向。

def reverseList(head):
    prev = None
    current = head
    while current:
        next_node = current.next
        current.next = prev
        prev = current
        current = next_node
    return prev

跳表

跳表是一种基于链表的数据结构,它通过引入多级索引来提高搜索效率。在 LeetCode 3 题中,我们要求设计一个跳表。首先,我们定义一个跳表节点,然后根据概率生成多级索引。

class Node:
    def __init__(self, key, val):
        self.key = key
        self.val = val
        self.next = [None] * level

class Skiplist:
    def __init__(self, p=0.5):
        self.header = Node(None, None)
        self.p = p
        self.level = 1

总结

数据结构与算法的学习并非一蹴而就,需要持之以恒。通过对 LeetCode 题目进行实践,我加深了对基本数据结构的理解,提高了算法分析和解决问题的能力。希望我的学习记录能够启发更多的人踏上数据结构与算法的探索之旅。