Problem
Solution
- Given: a sorted array
- Condition: Convert to wave array, where the elements are sorted in wave-like order (higher, lower, higher)
- Condition2: lexicographically smallest.
Given the values and conditions, we can solve the problem by simply swapping elements in the sorted array without the need for searching.
The condition "lexicographically smallest" implies using compareTo
for comparison, which is based on Unicode.
Therefore, we can solve the problem by simply iterating through half of the sorted array and swapping the current element with the previous even element.
Time Complexity: O(n), Space Complexity: O(1)
class Solution {
public static void convertToWave(int n, int[] a) {
// Iterate through the array starting from index 1 and incrementing by 2
// Swap the current element with the previous even element
for(int i = 1; i < n; i += 2){
// Swap the current element with the previous even element
int temp = a[i];
a[i] = a[i - 1];
a[i - 1] = temp;
}
}
}
댓글 없음:
댓글 쓰기