Given an integer array nums
, separate the numbers at even indices from those at odd indices. The indices must follow the following conditions:
Reconstruct the array by maintaining the original index structure but with the sorted even and odd index elements.
For example:
nums = [4,1,2,3]
nums = [2,3,4,1]
nums
contain negative numbers?
Here is the implementation in Python:
def sortEvenOdd(nums):
# Separate even and odd indexed elements
even_nums = [nums[i] for i in range(0, len(nums), 2)]
odd_nums = [nums[i] for i in range(1, len(nums), 2)]
# Sort even indexed elements in non-decreasing order
even_nums.sort()
# Sort odd indexed elements in non-increasing order
odd_nums.sort(reverse=True)
# Reconstruct the array
result = []
even_idx, odd_idx = 0, 0
for i in range(len(nums)):
if i % 2 == 0:
result.append(even_nums[even_idx])
even_idx += 1
else:
result.append(odd_nums[odd_idx])
odd_idx += 1
return result
# Example usage:
nums = [4, 1, 2, 3]
sorted_nums = sortEvenOdd(nums)
print(sorted_nums) # Output should be [2, 3, 4, 1]
O(n)
time.O(k log k)
time and the odd indexed list takes O(m log m)
time, where k
and m
are the lengths of these lists respectively. Since k + m = n
, the sorting operations are approximately O((n/2) log (n/2)) = O(n log n)
.O(n)
time.Thus, the overall time complexity is O(n log n)
.
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?