循环移动
来源:互联网 发布:excel表格怎样筛选数据 编辑:程序博客网 时间:2024/06/11 17:02
n个整数存入一维数组中,将该组数循环移动m位。
这个题看起来简单,真正实现起来并不是那么容易。这里介绍三个思路:
1、逐渐后移:
每次向后移动一次,共移动m次,将最后一位放在第一位,缺点:算法复杂度较高。
#include <stdio.h>int main(){int n,m, *a;int i,j,temp;scanf("%d",&n);a=new int [n];for(i=0;i<n;i++)scanf("%d",&a[i]);scanf("%d",&m);for(i=0;i<m;i++){temp=a[0];for(j=0;j<n-1;j++)a[j]=a[j+1];a[n-1]=temp;}for(i=0;i<n;i++)printf("%5d",a[i]);return 0;}
2、借助空间换取时间:
定义另外一个数组,循环一次即可,用空间换取时间。
#include <stdio.h>int main(){int n,m, *a,*b;int i,j,temp;scanf("%d",&n);a=new int [n];b=new int [n];for(i=0;i<n;i++)scanf("%d",&a[i]);scanf("%d",&m);for(i=0;i<n;i++)b[i]=a[(i+m)%n];for(i=0;i<n;i++)printf("%5d",b[i]);return 0;}
3、算法层面的思路:
假设给定的数字是1 2 3 4 5。假设向后移动2位,则将前2位逆置,将后3位逆置,最后整体逆置。过程如下:
2 1 3 4 5
2 1 5 4 3
3 4 5 1 2
参考代码如下:
#include <stdio.h>int reverse(int a[], int begin, int end){int low,high,temp;low=begin; high=end;while(low<high){temp=a[low];a[low]=a[high];a[high]=temp;low++; high--;}return 0;}int main(){int n,m, *a;int i;scanf("%d",&n);a=new int [n];for(i=0;i<n;i++)scanf("%d",&a[i]);scanf("%d",&m);reverse(a,0,m-1);reverse(a,m,n-1);reverse(a,0,n-1);for(i=0;i<n;i++)printf("%5d",a[i]);return 0;}
1 0
- 循环移动
- 循环移动
- 循环移动
- 循环移动
- 循环移动
- 循环移动
- 循环移动的图片
- 循环移动的图片
- 数组数据循环移动
- 循环移动问题思考!
- 循环移动字符串
- 循环移动数组元素
- 字符串循环移动
- 字符串循环移动
- 纹理贴图循环移动
- 循环移动字符串
- 数组循环移动
- 循环移动背景类
- linux之SQL语句简明教程---BETWEEN
- hdu4539郑厂长系列故事——排兵布阵 dp+状态压缩
- 使用c99编译出警告信息:implicit declaration of function ‘usleep’
- 2014-12-13迷宫的最短路径
- IOS动态字母键盘
- 循环移动
- 基金上周调研21家公司 最爱看电子元件企业
- 单例设计模式总结
- 在 linux 下使用 CMake 构建应用程序
- mysql 安装完成后登陆不了mysql的 shell 即mysql>遇到:ERROR 1045 (28000): Access denied for user 'root'@'localhost‘
- OpenStack之路: OpenStack架构设计指南 - 概述(摘录并翻译)
- [LeetCode] Best Time to Buy and Sell Stock
- 数据库事务以及JDBC事务隔离级别
- weblogic自动部署没有生效的情况