Given an array of integers, sort it so that all odd numbers appear before all even numbers. Within the odd segment the numbers must be in ascending order; within the even segment the numbers must be in descending order.
We provide two tidy approaches: (1) partition the array into odd and even segments, then sort each segment; (2) sort the whole array using a custom comparator that enforces parity and the required order.
All valid outputs place odds before evens. If we first partition the array so that odds occupy the prefix and evens the suffix, we only need to sort the prefix ascending and the suffix descending.
#include<vector>#include<algorithm>classSolution {
public: std::vector<int> sortOddEven(std::vector<int> nums) {
int n = nums.size();
int l =0, r = n -1;
while (l <= r) {
if (nums[l] %2!=0) { ++l; continue; }
if (nums[r] %2==0) { --r; continue; }
std::swap(nums[l++], nums[r--]);
}
int m = l; // first index of even (or n if none)
std::sort(nums.begin(), nums.begin() + m); // odds ascending
std::sort(nums.begin() + m, nums.end(), std::greater<int>()); // evens descending
return nums;
}
};
from typing import List
classSolution:
defsortOddEven(self, nums: List[int]) -> List[int]:
n = len(nums)
l, r =0, n -1while l <= r:
if nums[l] %2!=0:
l +=1continueif nums[r] %2==0:
r -=1continue nums[l], nums[r] = nums[r], nums[l]
l +=1 r -=1 m = l
nums[:m] = sorted(nums[:m])
nums[m:] = sorted(nums[m:], reverse=True)
return nums
⏰ Time complexity: O(n log n) — partition is O(n) and sorting the two segments dominates (O(m log m + (n-m) log(n-m)), worst-case O(n log n)).
🧺 Space complexity: O(1) extra if sorts are in-place (C++, Java in-place); Python/Go/Java may allocate temporary space for sorting depending on implementation.
Sort the whole array with a comparator that places odd numbers before even numbers; when comparing two odds use ascending order, when comparing two evens use descending order.
#include<vector>#include<algorithm>classSolution {
public: std::vector<int> sortOddEven(std::vector<int> nums) {
std::sort(nums.begin(), nums.end(), [](int a, int b){
bool ao = (a &1), bo = (b &1);
if (ao != bo) return ao > bo; // odd (1) should come before even (0)
if (ao) return a < b; // both odd -> ascending
return a > b; // both even -> descending
});
return nums;
}
};