(Several variants: e.g., rearrange max/min alternately)
- Two Pointer
- Sorting
For sorted array, use two pointers from ends and place elements alternately into new array, or use in-place encoding trick.
O(n)
O(n) or O(1) with encoding tricks
class Solution {
public int[] rearrange(int[] nums) {
int n = nums.length;
Arrays.sort(nums);
int[] res = new int[n];
int l = 0, r = n - 1, idx = 0;
while (l <= r) {
if (idx < n) res[idx++] = nums[r--];
if (idx < n) res[idx++] = nums[l++];
}
return res;
}
}