本文首发于 每日一题:1 - 咸鱼Blog
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]
Explanation:因为 nums[0] + nums[1] == 9 ,返回 [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]
Constraints:
-
2 <= nums.length <= 104
-
-109 <= nums[i] <= 109
-
-109 <= target <= 109
-
Only one valid answer exists.
Solution code
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
if (numsSize==0)return NULL;
for(int i=0;i<numsSize-1;i++){
if(nums[numsSize-1]+nums[i]==target){
int *result=(int*)malloc(sizeof(int)*2);
result[0]=i;
result[1]=numsSize-1;
*returnSize=2;
return result;
}
}
return twoSum(nums,numsSize-1,target,returnSize);
}
Note:
这种方式复杂度是,每次找到最后一个数字,判断前面每个数字与其相加是否符合,如果全部不符合,则标记的数组长度简短,逻辑上删除最后一个元素。
想要得到更优的复杂度,可以采取这样的方式:
-
table_sort,对其进行大小排序的同时不打乱位置,在排序过程中采取quick_sort可以达到平均复杂度;
-
排序后,分别从两头向中间逼近,如果两个和大于目标,则达头的指针内移,小于目标则小头指针内移;在遇到找到目标位置或者两个指针相遇后,离开循环,复杂度;
-
因此总的复杂度为.
-
但是空间复杂度明显增加