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]
}
相关推荐
哎写bug的程序员10 小时前
leetcode复盘(1)
算法·leetcode·职场和发展
雨师@12 小时前
ATM 模拟器 Golang 程序--示例
开发语言·后端·golang
qq_5344525212 小时前
【算法 day02】LeetCode 209.长度最小的子数组 | 59.螺旋矩阵II
java·算法·leetcode·职场和发展
dying_man13 小时前
LeetCode--31.下一个排列
算法·leetcode
IC 见路不走13 小时前
LeetCode 第75题:颜色分类
数据结构·算法·leetcode
Navigator_Z13 小时前
LeetCode //C - 757. Set Intersection Size At Least Two
c语言·算法·leetcode
你怎么知道我是队长17 小时前
GO语言---匿名函数
开发语言·后端·golang
不被定义的程序猿1 天前
Golang 在 Linux 平台上的并发控制
开发语言·后端·golang
GalaxyPokemon1 天前
LeetCode - 704. 二分查找
数据结构·算法·leetcode
ifanatic1 天前
[每周一更]-(第147期):使用 Go 语言实现 JSON Web Token (JWT)
前端·golang·json