剑指 Offer 21 调整数组顺序使奇数位于偶数前面
概述
https://leetcode-cn.com/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/
前后指针
class Solution {
public:
vector<int> exchange(vector<int>& nums) {
int l = 0;
int r = nums.size() - 1;
while (l < r) {
while (l < r && nums[l] % 2 == 1) l ++;
while (l < r && nums[r] % 2 == 0) r --;
if (l < r) {
int t = nums[l];
nums[l] = nums[r];
nums[r] = t;
l ++;
r --;
}
}
return nums;
}
};
Links: sword-offer-21