力扣141题-环形链表-python

本文介绍两种检测链表中是否存在环的有效方法:哈希表法和双指针法。哈希表法通过记录已访问节点判断环的存在,而双指针法则利用快慢指针在环形链表中必然相遇的特性进行检测。

题目描述

给定一个链表,判断链表中是否有环。

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/linked-list-cycle

示例

输入:head = [3,2,0,-4], pos = 1

输出:true

解释:链表中有一个环,其尾部连接到第二个节点。

图片来自力扣

题解

下面搬运部分官方算法说明与分析

方法一:哈希表

思路

我们可以通过检查一个结点此前是否被访问过来判断链表是否为环形链表。常用的方法是使用哈希表。

算法

我们遍历所有结点并在哈希表中存储每个结点的引用(或内存地址)。如果当前结点为空结点 null(即已检测到链表尾部的下一个结点),那么我们已经遍历完整个链表,并且该链表不是环形链表。如果当前结点的引用已经存在于哈希表中,那么返回 true(即该链表为环形链表)。

代码

# 哈希表法
def hasCycle(self, head): 
    set0 = set()
    while True:
        if head not in set0:
            set0.add(head)
            if head is None:
                return False
            else:
                head = head.next
        else:
            return True

复杂度分析

时间复杂度:O(n),对于含有 n 个元素的链表,我们访问每个元素最多一次。添加一个结点到哈希表中只需要花费 O(1) 的时间。

空间复杂度:O(n),空间取决于添加到哈希表中的元素数目,最多可以添加 n 个元素。

方法二:双指针

思路

想象一下,两名运动员以不同的速度在环形赛道上跑步会发生什么?

算法

通过使用具有 不同速度 的快、慢两个指针遍历链表,空间复杂度可以被降低至 O(1)O(1)。慢指针每次移动一步,而快指针每次移动两步。

如果列表中不存在环,最终快指针将会最先到达尾部,此时我们可以返回 false。

现在考虑一个环形链表,把慢指针和快指针想象成两个在环形赛道上跑步的运动员(分别称之为慢跑者与快跑者)。而快跑者最终一定会追上慢跑者。这是为什么呢?考虑下面这种情况(记作情况 A)- 假如快跑者只落后慢跑者一步,在下一次迭代中,它们就会分别跑了一步或两步并相遇。

其他情况又会怎样呢?例如,我们没有考虑快跑者在慢跑者之后两步或三步的情况。但其实不难想到,因为在下一次或者下下次迭代后,又会变成上面提到的情况 A。

代码

# 快慢指针法
def hasCycle(self, head):
    if head == None: return False
    slow = head
    fast = head
    while fast.next is not None and fast.next.next is not None:
        slow = slow.next
        fast = fast.next.next
        if slow == fast: return True
    return False

复杂的分析

时间复杂度 O(n).

空间复杂度 O(1).

完整代码

'''
leetcode 141.环形链表
'''
# Definition for singly-linked list.
class ListNode:

    def __init__(self, x):
        self.val = x
        self.next = None


class Solution:

    def hasCycle(self, head): # 不是空间复杂度为常量的哈希表算法
        set0 = set()
        while True:
            if head not in set0:
                set0.add(head)
                if head is None:
                    return False
                else:
                    head = head.next
            else:
                return True
    
    def hasCycle2(self, head): # 双指针算法
        if head == None: return False 
        slow = head
        fast = head
        while fast.next is not None and fast.next.next is not None:
            slow = slow.next
            fast = fast.next.next
            if slow == fast: return True
        return False
    
def creatListNode(head, pos):
    '''
    description:
        创建环形链表, head给出链表数值, pos指出链表尾巴链接到的位置
    parameter:
        head: type list
        pos: type int
    return:
        type: ListNode
    '''
    if head == []: return None
    temp0 = ListNode(head[0])
    out_head = temp0
    link = None

    for i in head[1:]:        
        if pos == 0: link = temp0
        pos -= 1
        
        temp1 = ListNode(i)
        temp0.next = temp1
        temp0 = temp1
    
    temp0.next = link
    return out_head

if __name__ == '__main__':
    
	head = [1, 5, 3, 0]
	pos = 1
	h = creatListNode(head, pos)
	
	solv = Solution()
	print(solv.hasCycle2(h))

参考链接

[1] 官方题解 https://leetcode-cn.com/problems/linked-list-cycle/solution/huan-xing-lian-biao-by-leetcode/

### 目解析与解法 LeetCode 热门 100 目是许多开发者和算法爱好者提升编程能力的重要资源。这些目涵盖了数组、字符串、链表、树、图、动态规划等多个领域。以下是一些代表性目的 Python 解法,结合了不同的算法思想和数据结构。 #### 1. 两数之和(Two Sum) 目要求找到数组中两个数的和等于目标值,并返回它们的索引。可以通过哈希表来优化查找过程,使得时间复杂度为 $O(n)$。 ```python class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: hash_map = {} for i, num in enumerate(nums): complement = target - num if complement in hash_map: return [hash_map[complement], i] hash_map[num] = i return [] ``` #### 2. 最长公共前缀(Longest Common Prefix) 该问要求找出一组字符串的最长公共前缀。可以通过逐字符比较的方法来解决,也可以使用 `zip` 函数来简化操作。 ```python class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: if not strs: return "" for i, chars in enumerate(zip(*strs)): if len(set(chars)) != 1: return strs[0][:i] return min(strs, key=len) ``` #### 3. 有效的括号(Valid Parentheses) 目要求判断括号是否有效。可以使用栈结构来解决,遇到左括号压入栈,遇到右括号时检查栈顶元素是否匹配。 ```python class Solution: def isValid(self, s: str) -> bool: stack = [] mapping = {")": "(", "}": "{", "]": "["} for char in s: if char in mapping.values(): stack.append(char) elif char in mapping: if not stack or mapping[char] != stack.pop(): return False return not stack ``` #### 4. 合并两个有序链表(Merge Two Sorted Lists) 将两个有序链表合并为一个新的有序链表。可以通过递归或迭代的方式实现。 ```python class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1: return l2 elif not l2: return l1 elif l1.val < l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next) return l2 ``` #### 5. 环形链表(Linked List Cycle) 判断链表中是否存在环。可以使用快慢指针法,快指针每次移动两步,慢指针每次移动一步,如果相遇则存在环。 ```python class Solution: def hasCycle(self, head: ListNode) -> bool: slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: return True return False ``` #### 6. 最长连续序列(Longest Consecutive Sequence) 找出数组中连续数字的最长长度。可以通过集合来优化查找,时间复杂度为 $O(n)$。 ```python class Solution: def longestConsecutive(self, nums: List[int]) -> int: num_set = set(nums) longest_streak = 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_streak = max(longest_streak, current_streak) return longest_streak ``` #### 7. 旋转数组(Rotate Array) 将数组向右旋转 $k$ 次。可以通过切片操作实现,注意 $k$ 需要对数组长度取模。 ```python class Solution: def rotate(self, nums: List[int], k: int) -> None: k = k % len(nums) res = nums[-k:] + nums[:-k] for i in range(len(nums)): nums[i] = res[i] ``` #### 8. 有效的数独(Valid Sudoku) 判断一个数独是否有效。需要检查每一行、每一列以及每一个 $3 \times 3$ 的子格。 ```python class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: rows = [{} for _ in range(9)] columns = [{} for _ in range(9)] boxes = [{} for _ in range(9)] for i in range(9): for j in range(9): num = board[i][j] if num != '.': num = int(num) box_index = (i // 3) * 3 + j // 3 rows[i][num] = rows[i].get(num, 0) + 1 columns[j][num] = columns[j].get(num, 0) + 1 boxes[box_index][num] = boxes[box_index].get(num, 0) + 1 if rows[i][num] > 1 or columns[j][num] > 1 or boxes[box_index][num] > 1: return False return True ``` #### 9. 三数之和(3Sum) 找出数组中所有三个数的和为零的组合。可以通过排序和双指针法来解决。 ```python class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() res = [] n = len(nums) for i in range(n): if i > 0 and nums[i] == nums[i - 1]: continue left, right = i + 1, n - 1 while left < right: total = nums[i] + nums[left] + nums[right] if total == 0: res.append([nums[i], nums[left], nums[right]]) while left < right and nums[left] == nums[left + 1]: left += 1 while left < right and nums[right] == nums[right - 1]: right -= 1 left += 1 right -= 1 elif total < 0: left += 1 else: right -= 1 return res ``` #### 10. 接雨水(Trapping Rain Water) 计算可以接住的雨水量。可以通过双指针法或动态规划实现。 ```python class Solution: def trap(self, height: List[int]) -> int: if not height: return 0 left, right = 0, len(height) - 1 left_max, right_max = height[left], height[right] water_trapped = 0 while left < right: if height[left] < height[right]: left += 1 left_max = max(left_max, height[left]) water_trapped += max(0, left_max - height[left]) else: right -= 1 right_max = max(right_max, height[right]) water_trapped += max(0, right_max - height[right]) return water_trapped ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值