題目
給定一個整數(shù)數(shù)組 nums 和一個目標(biāo)值 target,請你在該數(shù)組中找出和為目標(biāo)值的那 兩個 整數(shù),并返回他們的數(shù)組下標(biāo)。
你可以假設(shè)每種輸入只會對應(yīng)一個答案。但是,你不能重復(fù)利用這個數(shù)組中同樣的元素。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因?yàn)?nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解題思路
本道題目考察的知識點(diǎn):
- 循環(huán)判斷條件的掌握;
- 局部變量的作用域,涉及到靜態(tài)局部變量;
我的解答
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
static int a[2] = {0};
int i = 0, j = 0;
for (i = 0; i < numsSize - 1; i++)
{
for (j = i + 1; j < numsSize; j++)
{
if (target == nums[i] + nums[j])
{
a[0] = i;
a[1] = j;
return a;
}
}
}
return 0;
}