s*******n 发帖数: 97 | 2 如果非要O(n) in place, 看来只能借助system stack了,也就是说recusive调用的
stack不算addtional space.
For example, A = {2,3,6,7,4,5,8,10}
void oddeven(int[] a, int index, int oddpos){
if(index >= a.length){
把所有的偶数swap到数组的最右侧,O(n) time.
A = {7,3,5,2,6,4,8,10}
}
if(a[index]%2 == 1){
int odd = a[index];
oddeven(a, index + 1, oddpos + 1);
a[oddpos] = odd;
}else{
oddeven(a, index + 1, oddpos);
}
}
should work...
at |
|