來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/two-sum
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
題目
給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。
你可以假設每種輸入只會對應一個答案。但是,數組中同一個元素不能使用兩遍。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因爲 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]。
方法1:兩個for嵌套,依次取出2個數據判斷和是否是目標值,如果是則申請一塊內存a,將兩個元素的下標放入a中返回。如不是則進行下一次循環。這種方法要注意儘可能減少循環的次數。
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
if(numsSize < 2){
return NULL;
}
int *ret = NULL;
int i = 0,j = 0;
for(i = 0;i < numsSize - 1;i++){
for(j = i + 1;j < numsSize;j++){
if(nums[i] + nums[j] == target){
//printf("nums[i]:%d nums[j]:%d\n",nums[i],nums[j]);
*returnSize = 2;
ret = (int*) malloc(sizeof(int) * (*returnSize));
if(!ret){
return NULL;
}
memset(ret , 0 ,sizeof(int) * (*returnSize));
ret[0] = i;
ret[1] = j;
return ret;
}
}
}
return NULL;
}
方法2:構造hash表,若存在hash[( num[i] + hashsize )/ hashsize] 和 hash[ target - num[i] + hashsize ) /hashsize ],則存在這樣的兩個數的和爲target.
#define MAX_SIZE 2048
int *twoSum(int *nums, int numsSize, int target, int *returnSize)
{
int i, hash[MAX_SIZE], *res = (int *)malloc(sizeof(int) * 2);
memset(hash, -1, sizeof(hash));
for (i = 0; i < numsSize; i++)
{
if (hash[(target - nums[i] + MAX_SIZE) % MAX_SIZE] != -1)
{
res[0] = hash[(target - nums[i] + MAX_SIZE) % MAX_SIZE];
res[1] = i;
*returnSize = 2;
return res;
}
hash[(nums[i] + MAX_SIZE) % MAX_SIZE] = i; //防止負數下標越界,循環散列
}
*returnSize = 0;
return res;
}