[leetcode] - 324. Wiggle Sort II

题意大致为将给定数组中的元素按形如nums[0] < nums[1] > nums[2] < nums[3]….这种样子排列,顺序没要求。

这道题O(1)时间复杂度和空间复杂度的最优解暂时没想出来,用蠢办法解决。方案为先复制当前数组,将复制的数组排序,然后以中位数为界将数组分为两部分,small part和large part。交替填入原始数组即可,这样做的原因是可以避免有值相同的数组挨在一起,以符合题目规则。

交替填入也得注意必须降序交替,否则任然有可能挨在一起。比如[4, 5, 5, 6]这一组如果升序交替填入任然是4、5、5、6,降序则为5、6、4、5

import java.util.Arrays;

/**
 * @author: decaywood
 * @date: 2016/01/29 11:24
 *
 * 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?
 */
public class WiggleSortII {

    public void wiggleSort(int[] nums) {

        int[] temp = Arrays.copyOfRange(nums, 0, nums.length);
        Arrays.sort(temp);
        int large = temp.length / 2 + (temp.length % 2 == 0 ? -1 : 0);
        int small = temp.length - 1;
        for (int i = 0, j = 1; i < temp.length; i+=2, j+=2) {
            if(j < temp.length) nums[j] = temp[small--];
            nums[i] = temp[large--];
        }
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值