由买买提看人间百态

topics

全部话题 - 话题: oddpos
(共0页)
c*****e
发帖数: 3226
1
来自主题: JobHunting版 - g phone interv--有没有o(n) 解法
void wiggleSort(int a[]) {
if (a == null || a.length <=1) return;
boolean oddPos = true;
int i=0;
while(i <= a.length-2) {
if ((oddPos && a[i] > a[i+1]) ||
(!oddPos && a[i] < a[i+1])) {
int t = a[i+1];
a[i+1] = a[i];
a[i] = t;
}
i++;
oddPos = !oddPos;
}
}
s*******n
发帖数: 97
2
来自主题: JobHunting版 - 问一个题目,面试时我没有搞出来
如果非要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
(共0页)