数组移动问题

#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).


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值