01-E-4 数组倒置
#数据结构邓神
Q: 任给数组 A[0,n) 将其前后颠倒
统⼀接⼝:
void reverse(int* A,int lo,int hi);
// 将数组从 [lo,hi] 内部的所有元素反转
数组倒置:递归解决
void reverse(int* A,int lo,int hi){
if(lo < hi){ // 问题规模奇偶性不变,需要两个递归基
swap(A[lo],A[hi]);
reverse(A,lo+1,high-1);
}
}
迭代原始版
next: if(lo < hi){
swap(A[lo],A[hi]);
lo++;hi--;
goto next;
}
迭代精简版
while(lo < hi){
swap(A[lo++],A[hi--]);
}
评论0