leetcode_初级算法——数组——旋转数组

#初级算法——数组——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会随机分配内存中的数。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值