【LeetCode with Python】 Rotate List

本文介绍了一个链表操作问题,即如何将链表向右旋转k个位置。通过一个具体的示例,1->2->3->4->5->NULL在k=2的情况下变为4->5->1->2->3->NULL,详细解释了实现这一操作的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

博客域名: http://www.xnerv.wang
原题页面: https://oj.leetcode.com/problems/rotate-list/
题目类型:
难度评价:★
本文地址: http://blog.youkuaiyun.com/nerv3x3/article/details/38929137

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.


class Solution:
    # @param head, a ListNode
    # @param k, an integer
    # @return a ListNode
    def rotateRight(self, head, k):
        if None == head or None == head.next:
            return head
        cur_head = head
        cur = head
        while k > 0:
            cur = cur.next
            if None == cur:
                return head
            k -= 1
        cur_tail = cur
        cur_head = cur.next
        if None == cur_head:
            return head
        cur = cur_head
        while None != cur.next:
            cur = cur.next
        cur.next = head
        cur_tail.next = None
        return cur_head

### LeetCode 热题 100 的 Python 实现 #### 数组旋转问题 对于数组旋转问题,可以通过切片操作来简化处理过程。具体来说,在给定一个整数 `k` 后,首先计算 `k % len(nums)` 来获取实际需要移动的位置数量。接着通过切片创建一个新的列表,该列表由原列表最后 `k` 个元素加上剩余部分组成。最后将新构建的结果赋值回原始列表。 ```python class Solution: def rotate(self, nums: list[int], k: int) -> None: """ Do not return anything, modify nums in-place instead. """ n = len(nums) k %= n nums[:] = nums[-k:] + nums[:-k] ``` 此方法利用了 Python 列表的强大功能,使得代码更加简洁高效[^1]。 #### 寻找两个数之和等于目标值的问题 当面对寻找两个不同位置上的数字使其相加得到特定的目标数值的任务时,一种直观的方法是对每一个可能的组合进行尝试匹配。然而这种双重循环的方式效率较低,时间复杂度达到了 O(n²),其中 n 是输入序列长度。为了提高性能,可以考虑采用哈希表存储已经访问过的元素及其索引,从而可以在常量时间内完成查询并减少不必要的重复工作。 ```python from typing import List class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: num_to_index = {} for index, value in enumerate(nums): complement = target - value if complement in num_to_index: return [num_to_index[complement], index] num_to_index[value] = index ``` 上述优化后的算法仅需一次遍历即可解决问题,并且平均情况下能够在线性时间内给出答案[^2]。 #### 查找最长不含重复字符子串 针对这个问题,滑动窗口技术被广泛应用。初始化左右指针指向字符串起始处,同时维护一个集合用于跟踪当前窗口内的唯一字符。随着右边界不断扩展直至遇到重复项,则收缩左边界直到再次满足条件为止;期间记录最大不重叠区间大小作为最终返回结果。 ```python def lengthOfLongestSubstring(s: str) -> int: charSet = set() l = 0 res = 0 for r in range(len(s)): while s[r] in charSet: charSet.remove(s[l]) l += 1 charSet.add(s[r]) res = max(res, r - l + 1) return res ``` 这段代码展示了如何有效地运用双端队列的思想去解决此类挑战性的题目[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值