兩數之和
給定一個整數數組 nums
和一個目標值 target
,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。
你可以假設每種輸入只會對應一個答案。但是,數組中同一個元素不能使用兩遍
### 解題思路
直接用兩個for循環,遍歷數組來判斷
int *result = (int *)malloc(sizeof(int) * 2);
用來給result分配兩個內存空間
然後就直接雙重for循環
如果找到兩個數,就將下標值直接賦值給數組result
返回即可
ps:本人是個小白,對於算法更是一竅不通,本文的代碼是來自於leetcode的
Jinyang Ding編寫的,不是本人自己寫的,我只是寫進博客當學習筆記
### 代碼
int *twoSum(int* nums, int numsSize, int target, int* returnSize){
int *result = (int *)malloc(sizeof(int) * 2);
for (int i = 0; i < numsSize - 1; i++)
{
for (int j = i + 1; j < numsSize; j++)
{
if (nums[i] + nums[j] == target){
result[0] = i;
result[1] = j;
*returnSize =2;
return result;
}
}
}
return result;
}
```