题解 | #调整数组顺序使奇数位于偶数前面(二)#
调整数组顺序使奇数位于偶数前面(二)
http://www.nowcoder.com/practice/0c1b486d987b4269b398fee374584fc8
双指针遍历 O(2n)
双指针模板:
1:
for(l++){
if() r--
}
2:
while(l<r){
if() l++;
if() r--;
}
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param array int整型vector
* @return int整型vector
*/
vector<int> reOrderArrayTwo(vector<int>& a) {
// write code here
int n=a.size();
int l=0,r=n-1;
while(l<r){
if(a[l]%2==0){
while((a[r]%2==0)&&l<r) r--;
if(a[r]%2==1&&l<r){
int t=a[l];
a[l]=a[r];
a[r]=t;
}
r--;
}
l++;
}
return a;
}
};