324. Wiggle Sort II (Medium)

https://leetcode.com/problems/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?

Hints

Solutions

public class Solution {
    public static void wiggleSort(int[] nums) {
        final int n = nums.length;
        int[] tem = new int[n];
        for (int i = 0; i < n; i++) {
            tem[i] = nums[i];
        }
        int mid = partition(tem, 0, n-1, n/2);
        int[] ans = new int[n];
        for (int i = 0; i < n; i++) {
            ans[i] = mid;
        }

        int l = 1, r = (n%2 == 0) ? n-2 : n-1;
        for (int i = 0; i < n; i++) {
            if (nums[i] < mid) {
                ans[r] = nums[i];
                r -= 2;
            } else if (nums[i] > mid) {
                ans[l] = nums[i];
                l += 2;
            }
        }
        for (int i = 0; i < n; i++) {
            nums[i] = ans[i];
        }
    }

    public static int partition(int[] nums, int l, int r, int rank) {
        int left = l, right = r;
        int now = nums[left];
        while (left < right) {
            while (left < right && nums[right] >= now) {
                right--;
            }
            nums[left] = nums[right];
            while (left < right && nums[left] <= now) {
                left++;
            }
            nums[right] = nums[left];
        }
        if (left - l == rank) {
            return now;
        } else if (left - l < rank) {
            return partition(nums, left + 1, r, rank - (left - l + 1));
        } else {
            return partition(nums, l, right - 1, rank);
        }
    }
}
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-04-15 19:01:27

results matching ""

    No results matching ""