Problem Description
Explanation:
To solve this problem, we can sort the array and then rearrange the elements in a "wiggle" pattern. In a "wiggle" pattern, the array elements alternate between being greater and smaller than their neighboring elements.
The algorithm involves sorting the array and then swapping adjacent elements starting from the second element. We swap every even-indexed element with the next element if it is smaller and swap every odd-indexed element with the next element if it is greater.
Algorithm:
- Sort the input array.
- Iterate over the array starting from index 1.
- If the current index is even and the element at the current index is greater than the previous element, swap them.
- If the current index is odd and the element at the current index is smaller than the previous element, swap them.
Time Complexity:
The time complexity of this algorithm is O(nlogn) due to the sorting step, where n is the number of elements in the array.
Space Complexity:
The space complexity of this algorithm is O(1) as we do not use any extra space apart from a few variables.
: :
Solutions
class Solution {
public void wiggleSort(int[] nums) {
Arrays.sort(nums);
for (int i = 1; i < nums.length - 1; i += 2) {
int temp = nums[i];
nums[i] = nums[i + 1];
nums[i + 1] = temp;
}
}
}
Related LeetCode Problems
Loading editor...