惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
V
Visual Studio Blog
P
Privacy International News Feed
月光博客
月光博客
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
L
Lohrmann on Cybersecurity
N
News and Events Feed by Topic
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Apple Machine Learning Research
Apple Machine Learning Research
阮一峰的网络日志
阮一峰的网络日志
Webroot Blog
Webroot Blog
T
Threatpost
宝玉的分享
宝玉的分享
The Last Watchdog
The Last Watchdog
小众软件
小众软件
L
LINUX DO - 最新话题
C
Cisco Blogs
T
Troy Hunt's Blog
Schneier on Security
Schneier on Security
酷 壳 – CoolShell
酷 壳 – CoolShell
www.infosecurity-magazine.com
www.infosecurity-magazine.com
雷峰网
雷峰网
G
GRAHAM CLULEY
有赞技术团队
有赞技术团队
Know Your Adversary
Know Your Adversary
博客园 - 叶小钗
罗磊的独立博客
V
V2EX
博客园 - Franky
P
Proofpoint News Feed
SecWiki News
SecWiki News
腾讯CDC
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Jina AI
Jina AI
博客园 - 三生石上(FineUI控件)
S
Secure Thoughts
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Google DeepMind News
Google DeepMind News
Attack and Defense Labs
Attack and Defense Labs
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
PCI Perspectives
PCI Perspectives
V2EX - 技术
V2EX - 技术
Google DeepMind News
Google DeepMind News
Last Week in AI
Last Week in AI
aimingoo的专栏
aimingoo的专栏
Cisco Talos Blog
Cisco Talos Blog
N
News and Events Feed by Topic
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
S
SegmentFault 最新的问题

博客园 - vcfly

理解性记忆const修饰普通变量和指针的新思路 - vcfly - 博客园 戏剧性的中超2008, 戏剧性的最后四轮,戏剧性的过程, 如我所愿的结果 Gmail换界面了 Hold fast and let go ... 一道逻辑推理题: 猜生日 刚听了许巍的<<风行>>和<<故事>>, 软件开发之胡言乱语5-团队协作 软件开发之胡言乱语4: 实践与软件开发 Google is turning 10 软件开发之胡言乱语3-代码质量 软件开发之胡言乱语2 软件开发之胡言乱语1 决定个人软件质量高低的几个因素 调查: 哪些windows应用软件是用C#写的?哪些网站是用Asp.net写的? ZZ:<<给新人程序员的八点建议>> 越来越看不懂<<程序员>>... 写程序就像是上厕所 谁说Gmail不需要删邮件?! 单位门口的门卫
数组 循环位移 或 循环移动 (左移 或 右移) K位
vcfly · 2008-11-07 · via 博客园 - vcfly

指定一个数组,比如整数或字符串, 长度为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;
}