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; //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;
}发布于 2016-11-24 06:03:36
如果您有一个具有n元素的数组,那么访问该数组元素的有效索引范围是[0, n-1]。
因此,在大多数情况下,程序中的循环使用的索引范围无效。
另外,您为两个嵌套循环使用了相同的变量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迭代次数。
发布于 2017-09-11 20:32:34
你的循环是这样的
for(a_i=0; a_i<k; a_i++)
{
int temp=a[0];
for(a_j=0; a_j<n-1; a_j++)
{
a[a_j] = a[a_j+1];
}
a[n-1] = temp;
}
for(a_i=0 ; a_i<n ; a_i++)
{
printf("%d ",a[a_i]);
}发布于 2017-12-14 21:13:32
试试这段代码,让数组向左旋转d倍,这对你有帮助!!
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author Bilakhiya
*/
public class LeftRotate {
/**
* @param args the command line arguments
*/
static ArrayList<Integer> leftarray(ArrayList<Integer>A1,int n,int d)
{
for(int j=0;j<d;j++)
{
leftby1(A1,n);
}
return A1;
}
static ArrayList<Integer> leftby1(ArrayList<Integer>A1,int n)
{
int i,temp;
temp=A1.get(0);
for(i=0;i<n-1;i++)
{
A1.set(i,A1.get(i+1) );
}
A1.set(i,temp);
return A1;
}
public static void main(String[] args) {
// TODO code application logic here
ArrayList<Integer> A=new ArrayList<>();
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int d=sc.nextInt();
for(int i=0;i<n;i++)
{
A.add(sc.nextInt());
}
ArrayList<Integer> B=leftarray(A,n,d);
for(int i=0;i<n;i++)
{
System.out.print(B.get(i)+" ");
}
}
}https://stackoverflow.com/questions/40774788
复制相似问题