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
相关推荐
2402_854808378 小时前
如何管理微服务下Oracle的数据库连接数_调整应用节点的MaxActive汇总以防止超processes
jvm·数据库·python
慕涯AI8 小时前
Agent 30 课程开发指南 - 第16课
人工智能·python
Shorasul8 小时前
如何修改数据库实例名_ORACLE_SID环境变量重命名实战
jvm·数据库·python
2301_803538959 小时前
如何在 Go 中精确安装指定版本的模块.txt
jvm·数据库·python
Greyson19 小时前
如何利用RMAN修复逻辑坏块_VALIDATE CHECK LOGICAL验证块内结构损坏
jvm·数据库·python
6Hzlia9 小时前
【Hot 100 刷题计划】 LeetCode 300. 最长递增子序列 | C++ 动态规划 & 贪心二分
c++·leetcode·动态规划
6Hzlia9 小时前
【Hot 100 刷题计划】 LeetCode 72. 编辑距离 | C++ 经典 DP 增删改状态转移
c++·算法·leetcode
穿条秋裤到处跑9 小时前
每日一道leetcode(2026.04.16):距离最小相等元素查询
算法·leetcode·职场和发展
赵优秀一一9 小时前
SQLAlchemy学习记录
开发语言·数据库·python
m0_640309309 小时前
如何在phpMyAdmin中生成XML格式导出_与其他企业系统的数据交互
jvm·数据库·python