Leetcode

Wiggle Sort

  • Time:O(n)
  • Space:O(1)

C++

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]);
  }
};

JAVA

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;
  }
}

Python

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]