My solution:
1. Use double pointers, one to traverse before and one to traverse backward, changing the position of even number in front and odd number in back
Words can use the swap function ,,,,
You can use while loop when i and j increase
class Solution {
public:
vector<int> exchange(vector<int>& nums) {
int i=0;
int j=nums.size()-1;
while(i<j){
if(nums[i]%2==0 && nums[j]%2==1){
int tmp=nums[i];
nums[i]=nums[j];
nums[j]=tmp;
}
if(nums[i]%2==1) i++;
if(nums[j]%2==0) j--;
}
return nums;
}
};
2. It is also a double pointer, using the swap function, while loop
class Solution {
public:
vector<int> exchange(vector<int>& nums) {
int i=0;
int j=nums.size()-1;
while(i<j){
if(nums[i]%2==0 && nums[j]%2==1)
swap(nums[i],nums[j]);
while(i<j&&nums[i]%2==1) i++;
while(i<j&&nums[j]%2==0) j--;
}
return nums;
}
};