324-摆动排序II

Description

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?


问题描述

给定一个未排序的数组,重新对其排序, 使得nums[0] < nums[1] > nums[2] < nums[3]…


问题分析

先对nums排序,copy为nums的拷贝。
将copy的右半部分放入nums中以1开始, 间隔为2的位置
将copy的左半部分放入nums中以0开始, 间隔为2的位置
注意,两次操作都为逆序。否则,由于nums中间的元素相等会出错


解法

class Solution {
    public void wiggleSort(int[] nums) {
        Arrays.sort(nums);
        int[] copy = nums.clone();
        int index = 1;

        for (int i = nums.length - 1; i > (nums.length - 1) / 2; i--) {
            nums[index] = copy[i];
            index += 2;
        }

        index = 0;
        for (int i = (nums.length - 1) / 2; i >= 0; i--) {
            nums[index] = copy[i];
            index += 2;
        }
    }
}

你可能感兴趣的:(算法与数据结构,leetcode全解)