数组的左移问题
定义一个一维数组, 传入一个数字参数d, 令该数组中的所有元素循环向左移动d位(首位的元素移动到末尾,如此循环)
For Example:
Function Description
Complete the function rotLeft in the editor below. It should return the resulting array of integers.
rotLeft has the following parameter(s):
- An array of integers a a
- An integer , the number of rotations.
Input Format
The first line contains two space-separated integers n n and , the size of a a and number of left rotations you must perform.
The second line contains space-separated integers a[i] a [ i ] .
Constraints
- 1≤n≤105 1 ≤ n ≤ 10 5
- 1≤d≤n 1 ≤ d ≤ n
- 1≤a[i]≤106 1 ≤ a [ i ] ≤ 10 6
Output Format
Print a single line of n n space-separated integers denoting the final state of the array after performing left rotations.
Explanation
When we perform d=4 d = 4 left rotations,the array undergoes the following sequence of changes:
[1,2,3,4,5]→[2,3,4,5,1]→[3,4,5,1,2]→[4,5,1,2,3]→[5,1,2,3,4] [ 1 , 2 , 3 , 4 , 5 ] → [ 2 , 3 , 4 , 5 , 1 ] → [ 3 , 4 , 5 , 1 , 2 ] → [ 4 , 5 , 1 , 2 , 3 ] → [ 5 , 1 , 2 , 3 , 4 ]
using System;
using System.Collections.Generic;
class Solution {
// Complete the rotLeft function below.
static int[] rotLeft(int[] a, int d) {
/* 递归:stack overflow */
/* 语法简单,思路简单,但当大量数据计算时,会产生stack overflow(内存溢出)异常 */
//if(d == 0){
// return a;
//}
//int[] newArr = new int[a.Length];
//newArr[a.Length - 1] = a[0];
//for(int i = 1; i < a.Length; i++){
// newArr[i - 1] = a[i];
//}
//d--;
//return rotLeft(newArr, d);
/***********************************/
/* 循环:Terminated due to timeout */
/* 思路与递归写法类似,且有效的避免了大量数据运算时的内存异常,但是执行效率没有得到提升*/
/* 在Browser页面上执行时,如果遇到大量数据,有可能会产生Terminated due to timeout(连接超时)异常 */
//int[] newArr = new int[a.Length];
//while(d > 0){
// newArr = new int[a.Length];
// newArr[a.Length - 1] = a[0];
// for(int i = 1; i < a.Length; i++){
// newArr[i - 1] = a[i];
// }
// a = newArr;
// d--;
//}
//return a;
/***********************************/
/*直接定位:Learning From Hitscotty*/
/* 通过简单的算法,直接确定经过d次左移之后每个元素的索引位置 */
/* 效率高,不会产生上述两种异常。 */
/* PS:该方法是从用户名为Hitscotty的大佬哪里学习的 */
int[] newArr = new int[a.Length];
for(int i = 0; i < a.Length; i++){
int position = (i + (a.Length - d)) % a.Length;
newArr[position] = a[i];
}
return newArr;
}
static void Main(string[] args) {
//模拟数据
//之所以将其定义成string类型,是因为模拟大量数据测试时,方便直接从文本文档中读取数据,然后转换成int类型
string[] s = "1 2 3 4 5".Split(' ');
//将数据转换成int类型
int[] a = Array.ConvertAll(s, temp => Convert.ToInt32(temp));
//调用函数(传入数组、左移的位数)
rotLeft(a, 4);
}
}
Expected Output : 5 1 2 3 4