# [LeetCode] 280. Wiggle Sort 摆动排序

2021年09月15日 阅读数：3

Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....html

For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4].java

Java:post

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

Java:url

```public class Solution {
public void wiggleSort(int[] nums) {
if (nums == null || nums.length == 0) {
return;
}
for (int i = 1; i < nums.length; i++) {
if (i % 2 == 1) {
if (nums[i] < nums[i - 1]) {
swap(nums, i);
}
} else {
if (nums[i] > nums[i - 1]) {
swap(nums, i);
}
}
}
}

private void swap(int[] nums, int i) {
int tmp = nums[i - 1];
nums[i - 1] = nums[i];
nums[i] = tmp;
}
}　　```

Python:htm

```# Time:  O(n)
# Space: O(1)
class Solution(object):
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
for i in xrange(1, len(nums)):
if ((i % 2) and nums[i - 1] > nums[i]) or \
(not (i % 2) and nums[i - 1] < nums[i]):
# Swap unordered elements.
nums[i - 1], nums[i] = nums[i], nums[i - 1]
```

C++:blog

```// Time:  O(n)
// Space: O(1)
class Solution {
public:
void wiggleSort(vector<int>& nums) {
for (int i = 1; i < nums.size(); ++i) {
if (((i % 2) && nums[i] < nums[i - 1]) ||
(!(i % 2) && nums[i] > nums[i - 1])) {
// Swap unordered elements.
swap(nums[i], nums[i - 1]);
}
}
}
};　```

C++:排序

```// Time Complexity O(nlgn)
class Solution {
public:
void wiggleSort(vector<int> &nums) {
sort(nums.begin(), nums.end());
if (nums.size() <= 2) return;
for (int i = 2; i < nums.size(); i += 2) {
swap(nums[i], nums[i - 1]);
}
}
};
```

C++:element

```// Time Complexity O(n)
class Solution {
public:
void wiggleSort(vector<int> &nums) {
if (nums.size() <= 1) return;
for (int i = 1; i < nums.size(); ++i) {
if ((i % 2 == 1 && nums[i] < nums[i - 1]) || (i % 2 == 0 && nums[i] > nums[i - 1])) {
swap(nums[i], nums[i - 1]);
}
}
}
};
```

[LeetCode] Wiggle Sort II 摆动排序 II