#初级算法——数组——3旋转数组
数学
题目:
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入: [1,2,3,4,5,6,7] 和 k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右旋转 1 步: [7,1,2,3,4,5,6]
向右旋转 2 步: [6,7,1,2,3,4,5]
向右旋转 3 步: [5,6,7,1,2,3,4]
思路:
先把原来的数组复制过来,再依次把数组填入响应位置。。。可能有点绕的就是怎么去定义这个数组
void rotate(int* nums, int numsSize, int k){
int *nums_temp= calloc(numsSize + 1, sizeof(int)); ;
int i,j;
for(i=0;i<numsSize;i++)
{
nums_temp[i]=nums[i];
}
//copy the nums
for(j=0;j<numsSize;j++)
{
nums[(j+k)%numsSize]=nums_temp[j];
}
free(nums_temp);
}
之前直接定义了一个指针 int *nums_temp,结果出现报错
google一波------》以下是网上给出的解释:
When you are doing y[i], you dereference a NULL pointer which is not allowed and leads to an error. NULL represents a non-existing memory space so you can not store your ciphertext here !
To solve this problem you can declare and initialize y as follows :
char *y = calloc(strlen(t) + 1, sizeof(char)); // Ciphertext, ready to hold some data !
可以看出,我们定义一个指针,默认指向不存在的存储空间,也就是空指针。这样是没法访问这个地址的。calloc这个函数
函数名: calloc
函数原型:void *calloc(unsigned int nums,unsigned int size)
功能描述:在内存的动态存储中分配n个长度为size的连续内存空间,函数返回一个指向分配起始地址的指针,如果分配不成功就返回NULL。
这个函数与malloc的区别就是calloc会对内存空间做初始化,所有被初始化为0;而malloc会随机分配内存中的数。