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
相关推荐
少废话h6 小时前
解决Flink中ApacheCommonsCLI版本冲突
开发语言·python·pycharm
serve the people6 小时前
TensorFlow 图执行(tf.function)的 “非严格执行(Non-strict Execution)” 特性
人工智能·python·tensorflow
天命码喽c6 小时前
GraphRAG-2.7.0整合Milvus-2.5.1
开发语言·python·milvus·graphrag
吴佳浩8 小时前
LangChain 深入
人工智能·python·langchain
网安-轩逸11 小时前
回归测试原则:确保软件质量的基石
自动化测试·软件测试·python
Mr_Xuhhh11 小时前
YAML相关
开发语言·python
咖啡の猫11 小时前
Python中的变量与数据类型
开发语言·python
汤姆yu11 小时前
基于springboot的电子政务服务管理系统
开发语言·python
执笔论英雄12 小时前
【RL】python协程
java·网络·人工智能·python·设计模式
帮帮志13 小时前
【AI大模型对话】流式输出和非流式输出的定义和区别
开发语言·人工智能·python·大模型·anaconda