Swift solution - Sort O(n) time O(n) space


  • 0
    class Solution {
        func wiggleSort(_ nums: inout [Int]) {
            let sortedNums = nums.sorted()
            let count = nums.count
            var smalHalf = 0
            var bigHalf = (count - 1) / 2 + 1
            
            for i in stride(from: count - 1, through: 0, by: -1) {
                if i % 2 == 1 {
                    nums[i] = sortedNums[bigHalf]
                    bigHalf += 1
                } else {
                    nums[i] = sortedNums[smalHalf]
                    smalHalf += 1
                }
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.