数组循环移位

数组循环右移优化算法
本文介绍了一种高效实现数组循环右移操作的方法,仅使用两个额外变量,并保持时间复杂度为O(n)。

题目:把一个含有N个元素的数组循环右移k位,要求时间复杂度为O(n),只许使用两个附加变量。

#include <iostream>
#include <vector>
using namespace std;
int Reverse(int *a,int left,int right) {
    for(;left<right;left++,right--){
        int temp=a[left];
        a[left]=a[right];
        a[right]=temp;
    }
}
int RightShift(int *a,int N,int k){
    k=k%N;
    Reverse(a,0,N-k-1);
    Reverse(a,N-k,N-1);
    Reverse(a,0,N-1);
}
int Print(int *a,int N){
    if(a){
        for(int i=0;i<N;i++){
            cout<<a[i]<<" ";
        }
        cout<<endl;
    }
}
int main()
{
    int a[10]={0,1,2,3,4,5,6,7,8,9};
    Print(a,10);
    RightShift(a,10,4);
    Print(a,10);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值