数组 循环位移 或 循环移动 (左移 或 右移) K位

指定一个数组,比如整数或字符串, 长度为N, 将其循环右移K位.

以下是我的解法: 只需要遍历一次数组即可. 空间复杂度是o(1), 时间复杂度是o(N).
不同于其他的解法: 1) 不需要求GCD(N,K) 2)不需要遍历2遍数组(STL源码中的reverse算法)

void Output(int *pBuffer, int nCount)
{
    if(!pBuffer || !nCount) return;

    for (size_t i = 0; i < nCount; i++)
    {
        printf(" %d ", pBuffer[i]);
    }

    printf("\n");

}

void ShiftN(int *pBuffer, int nCount, int nShiftN)
{
    if(!pBuffer || !nCount || !nShiftN) return;

    nShiftN %= nCount;

    int nIndex = 0;
    int nStart  = nIndex;

    int nTemp  = pBuffer[nIndex];

    for (size_t i = 0; i < nCount; i++)
    {
        nIndex = (nIndex + nShiftN) % nCount;

        pBuffer[nIndex] ^= nTemp ^=
        pBuffer[nIndex] ^= nTemp ;

        if(nIndex == nStart)
        {
            nStart ++;
            nIndex = nStart;
            nTemp = pBuffer[nIndex];
        }
    }
}

int main(int argc, char* argv[])
{
    int buffer[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};

    int nCount = sizeof(buffer) / sizeof(int);

    Output(buffer, nCount);

    ShiftN(buffer, nCount, 8);

    Output(buffer, nCount);
   
    return 0;
}

转载于:https://www.cnblogs.com/vcfly/archive/2008/11/07/1328952.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值