【发布时间】:2021-04-28 16:29:33
【问题描述】:
class Solution{
public:
//Function to rotate an array by d elements in counter-clockwise direction.
void rotateArr(int arr[], int d, int n){
int i,j=0,l=0;
for(l=0;l<=d-1;l++){
int temp=arr[0];
for(i=0;i<=n;i++){
arr[i]=arr[i+1];
}
arr[i]=temp;
}
// code here
}
};
对于输入: 尺寸:5 旋转:2 1 2 3 4 5 预期产出 3,4,5,1,2 你的输出是: 3 4 5 32766 4196870
最后 2 个值作为垃圾值返回,我不知道为什么
【问题讨论】:
-
如果
n是数组的大小(元素数),那么循环条件i <= n将超出数组的范围。更不用说使用i + 1作为索引会在此之前超出范围。在内循环之后,i将 两 步超出范围(使用当前循环条件)。 -
仅供参考——如果
n是一个非常大的数字,您的解决方案就很差。考虑使用%(模数)。
标签: c++ arrays data-structures