The problem asks to reorder an integer array nums
such that nums[0] <= nums[1] >= nums[2] <= nums[3]...
. This means we need an alternating pattern of less than or equal to and greater than or equal to.
The most straightforward approach is a greedy one. We iterate through the array, comparing each element to its preceding element. If the pattern is violated (e.g., nums[i] < nums[i-1]
when i
is odd, or nums[i] > nums[i-1]
when i
is even), we swap the elements to restore the pattern. This ensures that after the loop, the array satisfies the wiggle sort condition.
class Solution:
def wiggleSort(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
for i in range(1, len(nums)):
if (i % 2 == 1 and nums[i] < nums[i - 1]) or (
i % 2 == 0 and nums[i] > nums[i - 1]
):
nums[i], nums[i - 1] = nums[i - 1], nums[i]
The Python code directly implements the greedy approach. The for
loop iterates from the second element. The if
condition checks if the current element violates the wiggle sort pattern based on its index (i % 2
). If a violation is found, a simple swap using tuple assignment (nums[i], nums[i - 1] = nums[i - 1], nums[i]
) corrects it. The function modifies the input array in-place, as specified.
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])) {
swap(nums, i, i - 1);
}
}
}
private void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}
The Java code is very similar to the Python version. It uses a helper function swap
to improve readability. The logic for checking the pattern and swapping elements remains the same.
class Solution {
public:
void wiggleSort(vector<int>& nums) {
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]);
}
}
}
};
The C++ code uses std::swap
for efficient swapping, but the overall algorithm remains consistent with the Python and Java versions.
func wiggleSort(nums []int) {
for i := 1; i < len(nums); i++ {
if (i%2 == 1 && nums[i] < nums[i-1]) || (i%2 == 0 && nums[i] > nums[i-1]) {
nums[i], nums[i-1] = nums[i-1], nums[i]
}
}
}
The Go code is a concise implementation, similar in structure to the Python code. It directly uses the tuple assignment for swapping.