Skip to content

280. Wiggle Sort 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
 public:
  void wiggleSort(vector<int>& nums) {
    // 1. If i is even, then nums[i] <= nums[i - 1].
    // 2. If i is odd, then nums[i] >= nums[i - 1].
    for (int i = 1; i < nums.size(); ++i)
      if ((!(i & 1) && nums[i] > nums[i - 1]) ||
          ((i & 1) && nums[i] < nums[i - 1]))
        swap(nums[i], nums[i - 1]);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public void wiggleSort(int[] nums) {
    // 1. If i is even, then nums[i] <= nums[i - 1].
    // 2. If i is odd, then nums[i] >= nums[i - 1].
    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]))
        swap(nums, i, i - 1);
  }

  private void swap(int[] nums, int i, int j) {
    final int temp = nums[i];
    nums[i] = nums[j];
    nums[j] = temp;
  }
}
1
2
3
4
5
6
7
8
class Solution:
  def wiggleSort(self, nums: List[int]) -> None:
    # 1. If i is even, then nums[i] <= nums[i - 1].
    # 2. If i is odd, then nums[i] >= nums[i - 1].
    for i in range(1, len(nums)):
      if not (i & 1) and nums[i] > nums[i - 1] or \
              (i & 1) and nums[i] < nums[i - 1]:
        nums[i], nums[i - 1] = nums[i - 1], nums[i]