c_cpp 由n个元素旋转数组

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 由n个元素旋转数组相关的知识,希望对你有一定的参考价值。

#include <iostream>
using namespace std;

void rotateByOne(int a[], int n){
	int i, temp = a[0];
	for(i=0; i<n-1; i++){
		a[i] = a[i+1];
	}
	a[i] = temp;
}
void rotate(int a[], int n, int d){
	for(int i=0; i<d; i++)
		rotateByOne(a, n);
}
int main() {
	int t, n, d;
	cin >> t;
	while(t--){
		cin >> n >> d;
		int a[101] = {0}, temp[101]={0};
		for(int i=0; i<n; i++)
			cin >> a[i];
		
		rotate(a, n, d);
	
		for(int i=0; i<n; i++)
			cout << a[i] << " ";
		cout << endl;
		
	}
	return 0;
}
/*
http://ideone.com/tKPU8B
http://www.geeksforgeeks.org/array-rotation/
http://www.practice.geeksforgeeks.org/problem-page.php?pid=360
*/

#include <iostream>
using namespace std;

int main() {
	// your code goes here
	int t, n, d;
	cin >> t;
	while(t--){
		cin >> n >> d;
		int a[n] = {0}, temp[d]={0};
		for(int i=0; i<n; i++)
			cin >> a[i];
		
		for(int i=0; i<=d; i++)
			temp[i] = a[i];
		
		int x = 0;
		for(int i=d; i<n; i++)
			a[x++] = a[i];
			
		for(int i=0; i<=d; i++)
			a[x++] = temp[i];
			
		for(int i=0; i<n; i++)
			cout << a[i] << " ";
		cout << endl;	
	}
	return 0;
}
/*
http://ideone.com/AuTwNV
http://www.practice.geeksforgeeks.org/problem-page.php?pid=924
*/

#include <iostream>
using namespace std;

void reverseArray(int a[], int start, int end){
	int temp;
	while(start < end){
		temp = a[start];
		a[start] = a[end];
		a[end] = temp;
		start++;
		end--;
	}
}
void rotate(int a[], int n, int d){
	reverseArray(a, 0, d-1);
	reverseArray(a, d, n-1);
	reverseArray(a, 0, n-1);
}
int main() {
	int t, n, d;
	cin >> t;
	while(t--){
		cin >> n;
		int a[101] = {0}, temp[101]={0};
		for(int i=0; i<n; i++)
			cin >> a[i];
		cin >> d;
		rotate(a, n, d);
	
		for(int i=0; i<n; i++)
			cout << a[i] << " ";
		cout << endl;
		
	}
	return 0;
}

以上是关于c_cpp 由n个元素旋转数组的主要内容,如果未能解决你的问题,请参考以下文章