数组:C中的左旋转 [英] Arrays: Left Rotation in C

查看:81
本文介绍了数组:C中的左旋转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

https://www.hackerrank.com/challenges/ctci-array -left-rotation



对大小为n的数组的左旋转操作将数组元素中的每个元素向左移动1个单位。例如,如果对数组[1,2,3,4,5]进行2次左旋转,则该数组将变为[3,4,5,1,2]



执行k转数并打印。



到目前为止,这是我得到的,但是只经历了一次交互,看不到我在做什么错

  int main(){
int n; // size
int k; //转数
int a_i; // index
scanf(%d%d,& n,& k);
int * a = malloc(sizeof(int)* n); //输入数组
for(a_i = 0; a_i< = n; a_i ++){
scanf(%d,& a [a_i]);
}

int temp;
for(a_i = 0; a_i< = k; a_i ++){
temp = a [0];
for(a_i = 0; a_i< n-1; a_i ++){
a [a_i] = a [a_i + 1];
}
a [a_i] = temp;
}

for(a_i = 0; a_i< n; a_i ++){
printf(%d,a [a_i]);
}


返回0;
}


解决方案

如果您有 n 个元素,则访问数组元素的索引的有效范围是 [0,n-1] 。 / p>

因此,在大多数情况下,程序中的循环使用无效的索引范围。



变量 a_i 的两个嵌套循环将为外部循环提供错误的索引

  for(a_i = 0; a_i< = k; a_i ++){
temp = a [0];
for(a_i = 0; a_i< n-1; a_i ++){
a [a_i] = a [a_i + 1];
}
a [a_i] = temp;
}

此语句

  for(a_i = 0; a_i< = k; a_i ++){

设置 k + 1 次迭代,而不是 k 次迭代。


https://www.hackerrank.com/challenges/ctci-array-left-rotation

A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. For example, if 2 left rotations are performed on array [1,2,3,4,5] , then the array would become [3,4,5,1,2]

Perform k number of rotations and print.

Here's what I got so far but it only goes through one interaction, don't see what I am doing wrong

int main(){
   int n; //size
   int k; //number of rotations
   int a_i; //index
   scanf("%d %d",&n,&k);
   int *a = malloc(sizeof(int) * n); //input array
   for(a_i = 0; a_i <= n; a_i++){
      scanf("%d",&a[a_i]);
   }

int temp;
for(a_i = 0; a_i <= k; a_i++){
    temp = a[0];
    for(a_i = 0; a_i < n-1; a_i++) {
        a[a_i] = a[a_i+1];
    }
    a[a_i] = temp;   
}

for(a_i = 0; a_i < n; a_i++){
    printf("%d ", a[a_i]);
}


return 0;
}

解决方案

If you have an array with n elements then the valid range of indices to access elements of the array is [0, n-1].

Thus the loops in your program in most cases use invalid ranges of indices.

Also you are using the same variable a_i for two nested loops that will give incorrect index for the outer loop

for(a_i = 0; a_i <= k; a_i++){
    temp = a[0];
    for(a_i = 0; a_i < n-1; a_i++) {
        a[a_i] = a[a_i+1];
    }
    a[a_i] = temp;   
}

Also this statement

for(a_i = 0; a_i <= k; a_i++){

sets k + 1 iterations instead of k iterations.

这篇关于数组:C中的左旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆