324. Wiggle Sort II

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

Example:
(1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6].
(2) Given nums = [1, 3, 2, 2, 3, 1], 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?

最朴素的方法是将数组排序分为两部分,将两部分分别放置在偶数位置和奇数位置。
为了满足OnO1,先利用findkth找到median,然后利用mapidx映射的关系将数组中元素置换。

public class Solution {
    public void wiggleSort(int[] nums) {
        if (nums == null || nums.length == 0) return;
        int n = nums.length;
        int median_idx = n % 2 == 0 ? n/2-1 : n/2;
        int median = findkth(nums, 0, nums.length-1, median_idx);
        int left = 0, right = n-1, i = 0;
        while (i <= right) {
            if (nums[mapidx(i, n)] > median) swap(nums, mapidx(i++, n), mapidx(left++, n));
            else if (nums[mapidx(i, n)] < median) swap(nums, mapidx(i, n), mapidx(right--, n));
            else i++;
        }

    }
    public int mapidx(int i, int n) {
        return (2 * i + 1) % (n | 1);
    }
    public int findkth(int[] nums, int start, int end, int k) {
        if (start > end) return Integer.MAX_VALUE;
        int pivot = nums[end];
        int left = start;
        for (int i = start; i < end; i++) {
            if (nums[i] < pivot) swap(nums, left++, i);
        }
        swap(nums, left, end);
        if (left == k) return nums[left];
        else if (left > k) return findkth(nums, start, left-1, k);
        return findkth(nums, left+1, end, k);

    }
    public void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值