zoukankan      html  css  js  c++  java
  • 1008. 数组元素循环右移问题

    题目截图:

    思路:

      先将整个数组逆置,然后将数组前 M 个元素和后面的元素分别逆置即可。

    代码:

     1 /*
     2     1008. 数组元素循环右移问题
     3 */
     4 
     5 #include <stdio.h>
     6 #include <string.h>
     7 #include <math.h>
     8 #include <stdlib.h>
     9 #include <time.h>
    10 
    11 #define maxn 101
    12 int p[maxn] = {0};
    13 
    14 // 逆置 
    15 void swap(int a, int b) {
    16     int i;
    17     for(i=a; i<=(a+b)/2; ++i) {
    18         int temp = p[i];
    19         p[i] = p[a+b-i];
    20         p[a+b-i] = temp;
    21     }
    22 }
    23 
    24 int main() {
    25     int N, M, i, flag=0;
    26     scanf("%d %d", &N, &M);
    27     M %= N;                    // M 可能大于 N 
    28     for(i=0; i<N; ++i) {
    29         scanf("%d", &p[i]);
    30     }
    31     if(M != 0) {            // M 为 0 不需要移动 
    32         swap(0, N-1);        // 逆置整个数组 
    33         swap(0, M-1);        // 逆置数组前 M 个元素 
    34         swap(M, N-1);        // 逆置数组后面元素 
    35     }
    36     for(i=0; i<N; ++i) {    // 按格式输出 
    37         if(flag) {
    38             printf(" ");
    39         }
    40         printf("%d", p[i]);
    41         flag = 1;
    42     }
    43 
    44     return 0;
    45 }
  • 相关阅读:
    PHP安装linux
    nginx 安装
    Redis安装
    linux启动http服务
    收藏的有用的网页
    laravel框架部署后有用命令
    .net 报错access to the path c: empimagefilesmsc_cntr_0.txt is denied
    oracle 触发器
    学习Auxre记录
    mysql数据库索引
  • 原文地址:https://www.cnblogs.com/coderJiebao/p/PAT1008.html
Copyright © 2011-2022 走看看