数组右移
来源:互联网 发布:手机天猫 手机淘宝 编辑:程序博客网 时间:2024/05/17 03:24
1.题目
假设有一个有 n 个元素的数组,求该数组右移 k 个元素后的数组,要求算法的空间复杂度为 O(1) 。
输入数据右三行,第一行表示数组元素个数 n ,第二行表示数组,第三行表示 k
7
1,2,3,4,5,6,7
3
输出
5,6,7,1,2,3,4
2.实现
分析:思路是,从最后一位开始,找到它要填的位置,再去寻找那个位置的数的新位置,重复直到找到某个数的新位置为最后一位。
#include<iostream>using namespace std;void moveArray(int arr[],int N,int k){k=k%N;//取当前变换的一位,从最后一位开始int currentIndex=N-1,currentVal=arr[N-1];do{//取到要变换的位置currentIndex=(currentIndex+k)%N;//交换当前值int temp=arr[currentIndex];arr[currentIndex]=currentVal;currentVal=temp;}while(N-1!=currentIndex);}int main(){int N,i,k,p;cin>>N;int a[N];for(i=0;i<N;i++) cin>>a[i];cin>>k;p=k%N;moveArray(a,N,k);for(i=0;i<N;i++) cout<<a[i]<<" ";return 0;}
实现的另一种方法(但是空间复杂度不满足了)
#include<iostream>using namespace std;int main(){int N,i,k;cin>>N;int a[N],b[N];for(i=0;i<N;i++) cin>>a[i];cin>>k;k=k%N;for(i=0;i<N;i++) b[(i+k)%N]=a[i];for(i=0;i<N;i++) cout<<b[i]<<" ";return 0;}
阅读全文
0 0
- 数组循环右移
- 数组右移
- 数组右移
- 数组右移
- 数组右移
- 数组循环右移
- 数组循环右移
- 数组循环右移
- LIST_数组右移
- 数组右移
- 数组的循环右移
- 数组循环右移算法
- 数组的循环右移
- 线性时间右移数组
- 数组的循环右移
- 数组的循环右移
- 数组的循环右移
- 数组的循环右移
- 56. Merge Intervals
- Python 是一门适合做数据挖掘的语言吗?
- 查找数据库中某一字段所在表
- 51node-1174-区间中最大的数(RMQ)
- ffmpeg音频处理——pcm格式与resample(重采样)
- 数组右移
- JAVA里的空白\t\n\r分别代表什么?
- 对象的比较comparable与comparator
- 环境变量配置
- android 长按监听
- python3爬虫基础学习
- Java 配置环境变量
- 三招两式,轻松搞定Excel文本算式
- 汇付科技新员工IT环境须知