324. Wiggle Sort II

Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3]....

You may assume the input array always has a valid answer.

 

Example 1:

Input: nums = [1,5,1,1,6,4]
Output: [1,6,1,5,1,4]
Explanation: [1,4,1,5,1,6] is also accepted.

Example 2:

Input: nums = [1,3,2,2,3,1]
Output: [2,3,1,3,1,2]

 

Constraints:

  • 1 <= nums.length <= 5 * 104
  • 0 <= nums[i] <= 5000
  • It is guaranteed that there will be an answer for the given input nums.

 

Follow Up: Can you do it in O(n) time and/or in-place with O(1) extra space?

Rust Solution

struct Solution;

impl Solution {
    fn wiggle_sort(nums: &mut Vec<i32>) {
        let n = nums.len();
        let mut sorted = nums.to_vec();
        sorted.sort_unstable();
        let k = if n % 2 == 0 { n / 2 } else { n / 2 + 1 };
        for i in 0..k {
            nums[i * 2] = sorted[k - 1 - i];
        }
        for i in 0..(n - k) {
            nums[i * 2 + 1] = sorted[n - 1 - i];
        }
    }
}

#[test]
fn test() {
    let mut nums = vec![1, 5, 1, 1, 6, 4];
    let res = vec![1, 6, 1, 5, 1, 4];
    Solution::wiggle_sort(&mut nums);
    assert_eq!(nums, res);
    let mut nums = vec![1, 1, 2, 1, 2, 2, 1];
    let res = vec![1, 2, 1, 2, 1, 2, 1];
    Solution::wiggle_sort(&mut nums);
    assert_eq!(nums, res);
    let mut nums = vec![4, 5, 5, 6];
    let res = vec![5, 6, 4, 5];
    Solution::wiggle_sort(&mut nums);
    assert_eq!(nums, res);
}

Having problems with this solution? Click here to submit an issue on github.