Leetcode 2164. Sort Even and Odd Indices Independently
You are given a 0-indexed integer array nums
. Reorder the array so that:
1, 3, 5, ...
) are sorted in descending order.0, 2, 4, ...
) are sorted in ascending order.Return the reordered array.
10^5
.#include <vector>
#include <algorithm>
std::vector<int> sortEvenOdd(std::vector<int>& nums) {
std::vector<int> evenElements;
std::vector<int> oddElements;
// Extract even-indexed and odd-indexed elements
for (int i = 0; i < nums.size(); ++i) {
if (i % 2 == 0) {
evenElements.push_back(nums[i]);
} else {
oddElements.push_back(nums[i]);
}
}
// Sort the even-indexed elements in ascending order
std::sort(evenElements.begin(), evenElements.end());
// Sort the odd-indexed elements in descending order
std::sort(oddElements.begin(), oddElements.end(), std::greater<int>());
// Place the sorted elements back in the array
int evenIndex = 0, oddIndex = 0;
for (int i = 0; i < nums.size(); ++i) {
if (i % 2 == 0) {
nums[i] = evenElements[evenIndex++];
} else {
nums[i] = oddElements[oddIndex++];
}
}
return nums;
}
n
is the size of the array.Overall, the time complexity is O(n log n) due to the sorting steps. The space complexity is O(n) for storing the odd and even 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?