C语言的指针是一大难点,理解了也就对C的基础没什么问题了。
只需要记住一点,指针就是地址
使用指针创建变量数组等就是开辟一个新的内存空间,这里就需要用到malloc
函数,这里是一个固定格式,记下即可
第一题
int* shuffle(int* nums, int numsSize, int n, int* returnSize){
int * res = (int *) malloc( sizeof(int) * n * 2);
*returnSize = numsSize;
for(int i = 0; i < n; ++i) {
res[i * 2] = nums[i];
}
for(int i = n; i < numsSize; ++i) {
res[2 * (i - n) + 1] = nums[i];
}
return res;
}
第二题
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* getConcatenation(int* nums, int numsSize, int* returnSize) {
int * ans = (int *) malloc( sizeof(int) * numsSize * 2 );
for(int i = 0; i < numsSize; i++) {
ans[i] = nums[i];
ans[i + numsSize] = nums[i];
}
*returnSize = 2 * numsSize;
return ans;
}
第三题
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* runningSum(int* nums, int numsSize, int* returnSize){
int * res = (int *) malloc( sizeof(int) * numsSize );
res[0] = nums[0];
for(int i = 1; i < numsSize; i++) {
res[i] = res[i - 1] + nums[i];
}
*returnSize = numsSize;
return res;
}
第四题
char* dynamicPassword(char* password, int target) {
int n = strlen(password);
char * res = (char *) malloc( sizeof(char) * (n + 1) );
for(int i = 0; i < n; i++) {
res[i] = password[(i + target) % n];
}
res[n] = '\0';
return res;
}