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

题目:

题解:

Go 复制代码
func wiggleSort(nums []int) {
    n := len(nums)
    x := (n + 1) / 2
    target := quickSelect(nums, x-1)

    transAddress := func(i int) int { return (2*n - 2*i - 1) % (n | 1) }
    for k, i, j := 0, 0, n-1; k <= j; k++ {
        tk := transAddress(k)
        if nums[tk] > target {
            for j > k && nums[transAddress(j)] > target {
                j--
            }
            tj := transAddress(j)
            nums[tk], nums[tj] = nums[tj], nums[tk]
            j--
        }
        if nums[tk] < target {
            ti := transAddress(i)
            nums[tk], nums[ti] = nums[ti], nums[tk]
            i++
        }
    }
}

func quickSelect(a []int, k int) int {
    rand.Seed(time.Now().UnixNano())
    rand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] })
    for l, r := 0, len(a)-1; l < r; {
        pivot := a[l]
        i, j := l, r+1
        for {
            for i++; i < r && a[i] < pivot; i++ {
            }
            for j--; j > l && a[j] > pivot; j-- {
            }
            if i >= j {
                break
            }
            a[i], a[j] = a[j], a[i]
        }
        a[l], a[j] = a[j], pivot
        if j == k {
            break
        } else if j < k {
            l = j + 1
        } else {
            r = j - 1
        }
    }
    return a[k]
}
相关推荐
x_xbx44 分钟前
LeetCode:26. 删除有序数组中的重复项
数据结构·算法·leetcode
j_xxx404_2 小时前
力扣困难算法精解:串联所有单词的子串与最小覆盖子串
java·开发语言·c++·算法·leetcode·哈希算法
big_rabbit05023 小时前
[算法][力扣167]Two Sum II
算法·leetcode·职场和发展
Eward-an3 小时前
LeetCode 76. 最小覆盖子串(详细技术解析)
python·算法·leetcode·职场和发展
不想看见4044 小时前
Reverse Bits位运算基础问题--力扣101算法题解笔记
笔记·算法·leetcode
逆境不可逃4 小时前
LeetCode 热题 100 之 394. 字符串解码 739. 每日温度 84. 柱状图中的最大矩形
算法·leetcode·职场和发展
重生之后端学习4 小时前
62. 不同路径
开发语言·数据结构·算法·leetcode·职场和发展·深度优先
big_rabbit05025 小时前
[算法][力扣283]Move Zeros
算法·leetcode·职场和发展
重生之后端学习5 小时前
64. 最小路径和
数据结构·算法·leetcode·排序算法·深度优先·图论
yiyaozjk5 小时前
Go基础之环境搭建
开发语言·后端·golang