翻转数组/循环移动类题

题目参见 PAT (Basic Level) Practice (中文) 1008 数组循环右移M个元素
 
核心函数
void reverse(int a[], int n, int begin, int end)
{
    int temp = 0;
    if (begin >= end)
        return;
    for (int i = begin; i <=(begin + end)/2; i++)
    {
        temp = a[i];
        a[i] = a[end - i+begin];
        a[end - i + begin] = temp;
    }
}

    int n, m,a[max];
    cin >> n >> m;
    m = m%n;//缩小到最小次数
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    reverse(a, n, 0, n - 1 - m);
    reverse(a, n, n-m, n-1);
    reverse(a, n, 0, n-1);
 
 
    for (int i = 0; i < n-1; i++)
    {
        cout << a[i] << ' ';
    }
    cout << a[n - 1];
posted @ 2020-03-12 11:17  ecnu_lxz  阅读(111)  评论(0编辑  收藏  举报