Leetcode in C-Two Sum 2021.1.4

學習筆記
1 min readJan 4, 2021

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Code:

/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int *answer=(int*)malloc(2*(sizeof(int)));
//static int answer[2];因為 如果返回值若為指針則可能會出現該錯誤,假如返回的指針地址指向函數內的局部變量,在函數退出時,該變量的存儲空間會被銷毀,此時去訪問該地址就會出現這個錯誤。

for(int i=0;i<numsSize;i++){
for(int j=i+1;j<numsSize;j++)
{
if(nums[i]+nums[j]==target){ printf("target:%d\n",target);
printf("%d%d\n",i,j);

answer[0]=i;
answer[1]=j;
*returnSize=2;
return answer;
}
}
}

*returnSize=0;
return NULL;
}

Output:

target:9
01
//return[0,1]
//answer[2]

--

--