这个专栏是为了记录在leetcode刷题过程的记录,便于查看。
题目1:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
int* twoSum(int* nums, int numsSize, int target)
{
int i = 0;
int j = 0;
int* res = (int*)malloc(sizeof(int) * 2);
int* temp = (int*)malloc(sizeof(int) * 200000); /* 相当于位图法,查找对应数时,无需进行比较,而是可以直接获得 */
int* temp_pos = (int*)malloc(sizeof(int) * 200000); /* 记录位图中数对应原数组的位置 */
int* bucket = &temp[100000]; /* 考虑存在负数的情况 */
int* bucket_pos = &temp_pos[100000];
for(i = 0; i < numsSize; i++)
{
bucket[nums[i]] = 1; /* 题目中假设答案只有一个,那么存在重复数字的肯定不是答案,其实也无需进行统计 */
bucket_pos[nums[i]] = i; /* 记录位置 */
}
for(i = 0; i < numsSize; i++)
{
if (bucket[target - nums[i]])
{
if (bucket_pos[target - nums[i]] == i) /* 例:i=0, nums[i]=3, target=6*/
{
continue;
}
res[0] = i + 1;
res[1] = bucket_pos[target - nums[i]] + 1;
break;
}
}
return res;
}