# Middle-题目113：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].

public class Solution {
public void wiggleSort(int[] nums) {
Arrays.sort(nums);
int[] temp = new int[nums.length];
int s = (nums.length + 1)/2, t = nums.length;
for (int i = 0; i < nums.length; i++) {
temp[i] = (i%2== 0) ?  nums[--s] : nums[--t] ;
}

for (int i = 0; i < nums.length; i++)
nums[i] = temp[i];
}
}

class Solution {
public:
void wiggleSort(vector<int>& nums) {
int n = nums.size();

// Find a median.
auto midptr = nums.begin() + n / 2;
nth_element(nums.begin(), midptr, nums.end());
int mid = *midptr;

// Index-rewiring.
#define A(i) nums[(1+2*(i)) % (n|1)]

// 3-way-partition-to-wiggly in O(n) time with O(1) space.
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++;
}
}
};

cmershen的碎碎念：

• 本文已收录于以下专栏：

举报原因： 您举报文章：Middle-题目113：324. Wiggle Sort II 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)