#include<stdio.h> void shiftleft(int *pInOut, int n) { int i; int tmp; tmp = *pInOut; for (i = 0; i < n - 1; ++i) { *pInOut = *(pInOut + 1); pInOut++; } *pInOut = tmp; } void shiftright(int *pInOut, int n) { int i; int tmp; pInOut += n - 1; tmp = *pInOut; for (i = n - 1 ; i > 0; --i) { *pInOut = *(pInOut - 1); --pInOut; } *pInOut = tmp; } void shiftN(int *pInOut, int n, int shiftN) { int i; if(shiftN > 0) { for(i = 0; i < shiftN % n; ++i) shiftleft(pInOut, n); } else { shiftN = -shiftN; for(i = 0; i < shiftN % n; ++i) shiftright(pInOut, n); } } int main() { int array[4] = {1, 2, 3, 4}; int array1[3] = {1, 2, 3}; int i; shiftN(array, 4, 5); for(i = 0; i < 4; ++i) printf("%d ",array[i]); printf("\n"); shiftN(array1, 3, -1); for(i = 0; i < 3; ++i) printf("%d ",array1[i]); printf("\n"); return 0; }
数组移动操作,写一个函数void shitfN(int *pInOut, int n, int shiftN),将pInOut指向的数组移动shiftN位,如果shiftN为正数,就左移,如果为负数就右移,n为数组的长度。例如,array[]={1, 2, 3, 4}, shiftN = 1,移动后的结果为,array[] ={ 2, 3, 4, 1}
如果array[]={1, 2, 3},shiftN = -1,移动后的结果为,array[]={3, 1, 2}
时间复杂度为o(ShiftN*n),换个方法思考:
循环左移ShiftN个,效果等价于,前ShiftN个元素逆置,后n-ShiftN个元素逆置,最后n个元素整体逆置。时间复杂度为o(n).