324. Wiggle Sort II

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

Example 1:

Input: nums = [1, 5, 1, 1, 6, 4]
Output: One possible answer is [1, 4, 1, 5, 1, 6].

Example 2:

Input: nums = [1, 3, 2, 2, 3, 1]
Output: One possible answer is [2, 3, 1, 3, 1, 2].

Note: You may assume all input has valid answer.

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

複製一份array,然後先sort原本的input,交替複製到tmp array裡。

// Naive Sort with Extra O(n) Space
void wiggleSort(vector<int>& nums) { // time: O(nlogn); space: O(n)
    vector<int> tmp = nums;
    sort(nums.begin(), nums.end());
    int n = nums.size(), j = n, k = (n + 1) / 2;
    for (int i = 0; i < n; ++i) {
        tmp[i] = (i & 1) ? nums[--j] : nums[--k];
    }
    nums = tmp;
}

利用nth_element這個std library裡的API,把數列分隔成前半小於最中間的數,後半大於最中間的數。但順序無法保證,只能確認midptr指到的數在應該在的位置。然後利用virtual indexing,把原本數列裡的odd indice連結到虛擬數列的前半indices,把原本數列裡的even indice連結到虛擬數列的後半indices,在操作3-way partition的時候,用虛擬數列來操作,目標是把前半數列變成大於mid,後半數列變成小於mid。

// Virtual Indexing and Three-Way Partition
void wiggleSort(vector<int>& nums) { // time: O(n); space: O(1)
    int n = nums.size();
    auto midptr = nums.begin() + n / 2;
    nth_element(nums.begin(), midptr, nums.end());
    int mid = *midptr;
    #define A(i) nums[(2 * i + 1) % (n | 1)]
    // virtual indexing
    // i in A -> (2*i + 1) % (n | 1) in nums
    // 0 -> 1
    // 1 -> 3
    // 2 -> 5
    // large indices in A correspond to odd indices in nums
    // small indices in A correspond to even indices in nums
    int i = 0, j = 0, k = n - 1;
    while (j <= k) {
        if (A(j) > mid) {
            swap(A(i++), A(j++));
        } else if (A(j) < mid) {
            swap(A(j), A(k--));
        } else {
            ++j;
        }
    }
}

Last updated

Was this helpful?