1152. Hop-Two Sort
A shelf holds n crates, and nums[i] is the weight of the crate in slot i. The only tool available is a small hoist that swaps the crates in slots i and i + 2. It can be used as many times as you like on any such pair of slots. Slots whose indices have different parity can never trade crates with each other, so each parity group is rearranged on its own.
Return true if some sequence of hoist swaps leaves the weights in non-decreasing order from slot 0 to slot n - 1, otherwise return false. Equal weights may stand next to each other. A shelf with one or two crates follows the same rule. Constraints: 1 <= n <= 1000 and -10^9 <= nums[i] <= 10^9. Aim for O(n log n) time and O(n) extra space.
Example 1
- Input:
- nums = [3,2,1]
- Output:
- true
- Explanation:
Positions 0 and 2 may swap, giving [1, 2, 3], which is sorted, so the answer is true.
Example 2
- Input:
- nums = [4,3,2,1]
- Output:
- false
- Explanation:
Even slots can only hold 4 and 2 and odd slots only 3 and 1, so the best layout is [2, 1, 4, 3], which is not sorted.
Example 3
- Input:
- nums = [1,2,3,4,5]
- Output:
- true
- Explanation:
The shelf is already in order, so no swap is needed.
Constraints
1 ≤ n ≤ 1000
-109 ≤ nums[i] ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n log n)
- Space
- O(n)