双指针1
从左右两头向中间查找
class Solution {
public:
vector<int> exchange(vector<int>& nums) {
int n=nums.size();
int pre=0,back=n-1;
while(pre<back){
if(nums[pre]%2==0&&nums[back]%2==1){
int temp=nums[pre];
nums[pre]=nums[back];
nums[back]=temp;
pre++;
back--;
}
while(nums[pre]%2==1&&pre<back)pre++;
while(nums[back]%2==0&&pre<back)back--;
}
return nums;
}
};
双指针2
从左向右查找
class Solution {
public:
vector<int> exchange(vector<int>& nums) {
int n=nums.size();
vector<int>out(n);
int pre=0,back=n-1;
for(int i=0;i<n;i++){
if(nums[i]%2==1){
out[pre]=nums[i];
pre++;
}else{
out[back]=nums[i];
back--;
}
}
return out;
}
};