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
相关推荐
Dxy12393102161 小时前
Python 条件语句详解
开发语言·python
龙泉寺天下行走1 小时前
Python 翻译词典小程序
python·oracle·小程序
践行见远2 小时前
django之视图
python·django·drf
love530love3 小时前
Windows避坑部署CosyVoice多语言大语言模型
人工智能·windows·python·语言模型·自然语言处理·pycharm
掘金-我是哪吒4 小时前
分布式微服务系统架构第132集:Python大模型,fastapi项目-Jeskson文档-微服务分布式系统架构
分布式·python·微服务·架构·系统架构
飞川撸码4 小时前
【LeetCode 热题100】739:每日温度(详细解析)(Go语言版)
算法·leetcode·golang
xhdll5 小时前
egpo进行train_egpo训练时,keyvalueError:“replay_sequence_length“
python·egpo
Cchaofan5 小时前
lesson01-PyTorch初见(理论+代码实战)
人工智能·pytorch·python
网络小白不怕黑5 小时前
Python Socket编程:实现简单的客户端-服务器通信
服务器·网络·python
Ronin-Lotus6 小时前
程序代码篇---python获取http界面上按钮或者数据输入
python·http