指定一個數組,比如整數或字符串, 長度為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;
}
posted on 2008-12-30 19:50
vcfly 閱讀(3562)
評論(2) 編輯 收藏 引用 所屬分類:
algorithm
、
c/c++