[LeetCode] Wiggle Sort

280. Wiggle Sort

Given an integer array nums, reorder it such that nums[0] <= nums[1] >= nums[2] <= nums[3]….

You may assume the input array always has a valid answer.

1
2
3
4
5
6
7
8
9
class Solution {
public:
void wiggleSort(vector<int>& nums) {
for(int i = 0; i < nums.size() - 1; i++) {
if(i & 1 and nums[i] < nums[i+1]) swap(nums[i],nums[i+1]);
else if(!(i&1) and nums[i] > nums[i+1]) swap(nums[i], nums[i+1]);
}
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/18/PS/LeetCode/wiggle-sort/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.