给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
提示1
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations.
提示2
So, if we fix one of the numbers, say
, we have to scan the entire array to find the next numberx
which isy
value - x
where value is the input parameter. Can we change our array somehow so that this search becomes faster?
提示3
The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
来源:力扣(LeetCode) 1. 两数之和
链接:https://leetcode-cn.com/problems/two-sum/
法一:暴力枚举
int* twoSum(int* nums, int numsSize, int target, int* returnSize)
{
int *arr = (int*)malloc(sizeof(int) * 2);
arr[0] = 0;
arr[1] = 0;
for(int i = 0; i < numsSize - 1; i++)
{
for(int j = i + 1; j < numsSize; j++ )
{
if(nums[i] + nums[j] == target)
{
arr[0] = i;
arr[1] = j;
*returnSize = 2;
return arr;
}
}
}
return arr;
}
法二:(源码改自力扣)步骤如下
- 判断特殊条件,如,数组为空或传入了空指针导致程序崩溃
- 构建新的数组储存原数列,并对新数组排序,使用了C标准库<stdlib.h>自带的qsort函数排序
- 利用类似折半查找的思想,从数组两边向内遍历
- 如果找到满足要求的值,利用循环与原数组对照找到所求的下标
int cmp(void const* a, void const* b) //qsort参数,泛型比较函数
{
return *(int*)a - *(int*)b;
}
int* twoSum(int* nums, int numsSize, int target, int* returnSize)
{
if(NULL == nums || numsSize == 0)
{
*returnSize = 0;
return NULL;
}
int* indexs = malloc(sizeof(int) * numsSize);
memset(indexs, 0 , numsSize);
for (int i = 0; i < numsSize; ++i)
{
indexs[i] = nums[i];
}
qsort(nums, numsSize, sizeof(nums[0]), cmp); //排序
int l = 0;
int r = numsSize - 1;
while (l < r)
{
if (nums[l] + nums[r] == target)
{
for (int i = 0; i < numsSize; ++i) //如果有满足要求的值,与原数组对照寻找对应下标
{
if (indexs[i] == nums[l])
{
l = i;
break;
}
}
for (int i = 0; i < numsSize; ++i) //同上
{
if (indexs[i] == nums[r] && i != l)
{
r = i;
break;
}
}
nums[0] = l;
nums[1] = r;
*returnSize = 2;
return nums;
}
else if (nums[l] + nums[r] > target)
{
r--;
}
else
{
l++;
}
}
*returnSize = 0;
return NULL;
}