同步发于 JuzerTech 网站,里面有我软、硬件学习的纪录与科技产品开箱,欢迎进去观看。
题目为输入一串数列,要寻找两个数字相加与目标值相同的数,并回传它们的位置。
原文题目如下
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].
下方为我使用 C 语言的解法
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int yn = -1;
*returnSize = 2;
int *arr = malloc(*returnSize * sizeof(int));
for(int i = 0;i<numsSize;i++){
for(int j = 0;j<numsSize;j++){
if(i!=j)
if(nums[i]+nums[j]==target){
arr[0] = i;
arr[1] = j;
yn = 1;
break;
}
}
if(yn==1)
break;
}
if(yn == -1){
*returnSize = 0;
free(arr);
}
return arr;
}