2019-04-01 11:36:16
*数组长度计算
int num[] = { 15,55,26,77,56 }; int len = sizeof(num) / sizeof(int); //sizeof(num)是计算整体数组的大小(以字节为单位) //sizeof(int)是计算一个int数据的大小(以字节为单位) /* 好处:避免人工计算出错 坏处:出错无法察觉 */
*数组传参
#include "stdio.h" #include "stdlib.h" int twosum(int num[]) { int i, j; i = sizeof(num); j = sizeof(int); int len = sizeof(num) / sizeof(int); printf("num 的大小:%d\n", i); printf("一个int 的大小:%d\n", j); printf("数组的长度:%d\n", len); return len; } int main() { int target = 9; int num[] = { 15,55,26,77,56 }; twosum(num); printf("-------------\n"); int i, j; i = sizeof(num); j = sizeof(int); int len = sizeof(num) / sizeof(int); printf("num 的大小:%d\n", i); printf("一个int 的大小:%d\n", j); printf("数组的长度:%d\n", len); system("pause"); return 0; }
结果:
出错原因:数组传递的是首地址地址,但是参数到了函数内就成了普通地址,不再是首地址。所以sizeof计算的是指针的大小。
*leetcode
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
int* twoSum(int* nums, int numsSize, int target) { int *a = (int*)malloc(2 * sizeof(int));//之前没有想到, int sum = 0;//前面的 (int *)是强制转换,后面的malloc(sizeof(int)); 是在内存中创建一个连续长度为2*sizeof(int)的区间之后再返回该区间的首地址给int * a for (int i = 0; i < numsSize - 1; i++) { for (int j = i + 1; j < numsSize; j++) { sum = nums[i] + nums[j]; if (sum == target) { a[0] = i; a[1] = j; } } } return a; }
常规解法就是穷举,所有数相加,然后进行判断。