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]
}
相关推荐
ttwuai2 天前
Go开源后台管理系统推荐:怎么按技术栈和边界比较4个官方仓库?
golang·gin
codeejun2 天前
每日一Go·MySQL-5、锁机制全解析
云原生·golang
旖旎夜光2 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
Achou.Wang2 天前
k8s中nginx worker process自动设置
后端·golang
CoderYanger3 天前
A.每日一题:835. 图像重叠
java·开发语言·程序人生·leetcode·面试·职场和发展·学习方法
圣保罗的大教堂3 天前
leetcode 3524. 求出数组的 X 值 I 中等
leetcode
Tim_103 天前
【LeetCode】338、比特位计数
c++·算法·leetcode
mmmmath_33 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Navigator_Z3 天前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.3 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode