虽然本科电子信息工程不教算法一类的课程,但为了将来日常工作,决定开始自学一些算法和数据结构知识。
就从LeetCode开始吧!
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
例如:给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
int* twoSum(int* nums, int numsSize, int target) {
int *a = (int*)malloc(2*sizeof(int));
for(int i=0;i<numsSize;i++)
for(int j=i+1;(j<numsSize && j!=i);j++)
{
if(nums[i]+nums[j]==target)
{
a[0]=i;
a[1]=j;
}
}
return a;
}
我采用了最简单的方法,通过2个For循环完成了遍历寻找。
收货:
int *a = (int*)malloc(2*sizeof(int));
这段代码是在动态分配内存,为int型指针a分配的2个int字节的空间。
新的开始,不断精进。