← 返回 oracle 的题目列表Sort Array by Parity — Minimum Swaps
类型:qbank
Rearrange an integer array so every even precedes every odd using arbitrary swaps, and return the minimum number of swaps. A two-pointer sweep from both ends gives the optimal count.
Requirements
Given an integer array, rearrange it so that every even number comes before every odd number.
Any two elements may be swapped; relative order within the evens or within the odds does not matter.
Return the minimum number of swaps needed to reach a valid arrangement.
A two-pointer pass from both ends — advance the left pointer past evens, advance the right pointer past odds, swap the mismatched pair and count one swap — yields the minimum.
Notes
The partition-by-parity base is equivalent to LeetCode 905; the twist is counting the minimum swaps rather than returning the reordered array.
The interviewer pushes hard on complexity and tends to interrupt the approach explanation to ask for Big-O — lead with O(n) time, O(1) space.