Python | Leetcode Python题解之第324题摆动排序II

题目:

题解:

python 复制代码
def quickSelect(a: List[int], k: int) -> int:
    seed(datetime.datetime.now())
    shuffle(a)
    l, r = 0, len(a) - 1
    while l < r:
        pivot = a[l]
        i, j = l, r + 1
        while True:
            i += 1
            while i < r and a[i] < pivot:
                i += 1
            j -= 1
            while j > l and a[j] > pivot:
                j -= 1
            if i >= j:
                break
            a[i], a[j] = a[j], a[i]
        a[l], a[j] = a[j], pivot
        if j == k:
            break
        if j < k:
            l = j + 1
        else:
            r = j - 1
    return a[k]

class Solution:
    def wiggleSort(self, nums: List[int]) -> None:
        n = len(nums)
        x = (n + 1) // 2
        target = quickSelect(nums, x - 1)

        transAddress = lambda i: (2 * n - 2 * i - 1) % (n | 1)
        k, i, j = 0, 0, n - 1
        while k <= j:
            tk = transAddress(k)
            if nums[tk] > target:
                while j > k and nums[transAddress(j)] > target:
                    j -= 1
                tj = transAddress(j)
                nums[tk], nums[tj] = nums[tj], nums[tk]
                j -= 1
            if nums[tk] < target:
                ti = transAddress(i)
                nums[tk], nums[ti] = nums[ti], nums[tk]
                i += 1
            k += 1
相关推荐
程序员清风31 分钟前
Python 数据分析环境搭建:从 Jupyter 到 pandas
python·jupyter·数据分析
月光船幽幽44 分钟前
加性偏移外推提升参数识别可靠性
python·算法
BD_Marathon1 小时前
消息对象中字段的说明
java·前端·python
Java后端的Ai之路2 小时前
Python进阶探索23 - Python中的Time与Datetime模块
开发语言·数据库·python·datetime·time
Java后端的Ai之路2 小时前
Python进阶探索24_应用案例_linux系统的监控
linux·开发语言·python·应用·探索
happylifetree2 小时前
Python22-26:核心语法-流程控制语句-if条件判断
python
程序员清风3 小时前
PydanticAI 实战:用类型安全构建可靠的 Python Agent
开发语言·python·安全
梦想画家3 小时前
SQLMesh Python 模型入门(三):前后置语句、蓝图建模与避坑指南
大数据·python·sqlmesh
迅猛龙办公室3 小时前
Python实现绘制同切圆
开发语言·python
言乐64 小时前
Python语音检索
开发语言·python·django·virtualenv·pygame