Loading problem...
You are given an integer array nums. Your task is to rearrange the elements in-place so that they follow an alternating wave pattern. In this pattern, each element at an odd index (1, 3, 5, ...) should be a local maximum, meaning it must be greater than or equal to its immediate neighbors.
Formally, after rearrangement, the array must satisfy:
nums[0] ≤ nums[1] ≥ nums[2] ≤ nums[3] ≥ nums[4] ≤ nums[5] ...In other words:
i, the element nums[i] should be greater than or equal to both nums[i-1] and nums[i+1] (if they exist).i, the element nums[i] should be less than or equal to both its neighbors (if they exist).The input is guaranteed to always have at least one valid rearrangement. If multiple valid arrangements exist, returning any one of them is acceptable.
Note: You must modify the array in-place and not return a new array.
nums = [3,5,2,1,6,4][3,5,1,6,2,4]The output satisfies the wave pattern: 3 ≤ 5 ≥ 1 ≤ 6 ≥ 2 ≤ 4. Alternative valid outputs like [1,6,2,5,3,4] or [2,5,1,6,3,4] would also be accepted.
nums = [6,6,5,6,3,8][6,6,5,6,3,8]This array already satisfies the wave pattern: 6 ≤ 6 ≥ 5 ≤ 6 ≥ 3 ≤ 8.
nums = [1,2,3,4,5][1,3,2,5,4]Rearranging the sorted array into wave pattern: 1 ≤ 3 ≥ 2 ≤ 5 ≥ 4. Other valid outputs like [1,2,1,5,3] would also work.
Constraints