Leetcode 2164. Sort Even and Odd Indices Independently
The problem is to sort the elements at even indices and odd indices of an array independently. Given an integer array nums, you need to perform the following operations:
Return the array after performing the above operations.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortEvenOddIndices {
public int[] sortEvenOdd(int[] nums) {
if (nums == null || nums.length <= 1) {
return nums; // Edge case for null or single-element arrays
}
List<Integer> evenIndices = new ArrayList<>();
List<Integer> oddIndices = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
if (i % 2 == 0) {
evenIndices.add(nums[i]);
} else {
oddIndices.add(nums[i]);
}
}
Collections.sort(evenIndices);
Collections.sort(oddIndices, Collections.reverseOrder());
int evenIndex = 0;
int oddIndex = 0;
for (int i = 0; i < nums.length; i++) {
if (i % 2 == 0) {
nums[i] = evenIndices.get(evenIndex++);
} else {
nums[i] = oddIndices.get(oddIndex++);
}
}
return nums;
}
// Example usage
public static void main(String[] args) {
SortEvenOddIndices solution = new SortEvenOddIndices();
int[] nums = {4, 1, 2, 3};
int[] sortedNums = solution.sortEvenOdd(nums);
for (int num : sortedNums) {
System.out.print(num + " ");
}
}
}
Therefore, the overall time complexity is (O(n \log n)).
The space complexity is (O(n)) for storing the even and odd indexed elements separately.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?