# Java O(n) 10 lines consice solution

• ``````public class Solution {
public void wiggleSort(int[] nums) {
for (int i = 1; i < nums.length; i++)
if ((i % 2 == 1 && nums[i] < nums[i - 1]) || (i % 2 == 0 && nums[i] > nums[i - 1])) {
int tmp = nums[i];
nums[i] = nums[i - 1];
nums[i - 1] = tmp;
}
}
}``````

• Thanks for sharing. But does it work for the following case?

int[] nums = {1,1,1,1,1,2,2,2,2,2};

• @happyLucia
Hi!
When I tried your case, the OJ just printed out "[1,1,1,1,1,2,2,2,2,2]".
But my another solution may work.

``````class Solution {
public:
void wiggleSort(vector<int>& nums) {
if (nums.empty()) {
return;
}
sort(nums.begin(), nums.end());
swap(nums.back(), nums[nums.size() / 2]);
if (nums.size() % 2) {
wiggleSort(nums, 0, nums.size() - 2);
} else {
wiggleSort(nums, 0, nums.size() - 1);
}
}
private:
void wiggleSort(vector<int>& nums, int l, int r) {
if (l < r - 1) {
int _size = r - l + 1, i = l + _size / 4, mid = l + _size / 2, j = l + 3 * _size / 4;
reverse(nums.begin() + i, nums.begin() + mid);
reverse(nums.begin() + mid, nums.begin() + j);
reverse(nums.begin() + i, nums.begin() + j);
wiggleSort(nums, l, l + 2 * (i - l) - 1);
wiggleSort(nums, l + 2 * (i - l), r);
}
}
};
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.