10.11. Peaks and Valleys
Description
In an array of integers, a "peak" is an element which is greater than or equal to the adjacent integers and a "valley" is an element which is less than or equal to the adjacent integers. For example, in the array {5, 8, 6, 2, 3, 4, 6}, {8, 6} are peaks and {5, 2} are valleys. Given an array of integers, sort the array into an alternating sequence of peaks and valleys.
Example:
Input: [5, 3, 1, 2, 3] Output: [5, 1, 3, 2, 3]
Note:
nums.length <= 10000
Solutions
Solution 1: Sorting
Thinking
The array must alternate peaks and valleys. Fixing adjacent inversions locally can break the other side.
After a full sort, swapping each even index with the next puts the larger value on odd indices: small, large, small, large.
nums.sort() then nums[i:i+2]=reversed(...) for even \(i\). Sorted pairs become peaks no lower than their neighbors.
We first sort the array, and then traverse the array and swap the elements at even indices with their next element.
The time complexity is \(O(n \times \log n)\), and the space complexity is \(O(\log n)\). Here, \(n\) is the length of the array.
1 2 3 4 5 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 | |
1 2 3 4 5 6 | |
1 2 3 4 5 6 7 8 9 10 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |