Questions:Two-Sum
My Answer:
/*
Function: Copynums
Explanation:
The function is used to judging whether a number is in nums or not.
*/
int* copynums(int* nums, int numsSize, int maxn, int minn)
{
int i;
int* cpnums;
cpnums = (int*)malloc((maxn-minn+1) * sizeof(int));
for (i = 0; i < maxn-minn; i++)
{
*(cpnums+i) = 0;
}
for (i = 0; i < numsSize; i++)
{
cpnums[nums[i]-minn] = 1;
}
return cpnums;
}
int* twoSum(int* nums, int numsSize, int target)
{
int* ans;
ans = (int*)malloc(5*sizeof(int));
int i, j;
int maxn = 0, minn = 0;
int pla1 = 0, pla2 = 0;
maxn = nums[0];
minn = nums[0];
for (i = 1; i < numsSize; i++)
{
if (nums[i] > maxn) maxn = nums[i];
if (nums[i] < minn) minn = nums[i];
}
int* cpnums = (int*)malloc((maxn-minn+1) * sizeof(int));
cpnums = copynums(nums, numsSize, maxn, minn);
for (i = 0; i < numsSize; i++)
{
int wanna = target - nums[i];
bool flag = false;
if (cpnums[wanna-minn] == 1) // the desire number is in nums
{
for (j = 0; j < numsSize; j++) // find its pla
{
if (nums[j] == wanna && i != j)
{
flag = true;
pla1 = i;
pla2 = j;
break;
}
}
}
if (flag) break;
}
ans[0] = pla1;
ans[1] = pla2;
return ans;
}
Complexity:O(n^2)
Examples
Examples_A:
Input:
[3,2,4]
6
Except Output:
[1,2]
Examples_B:
Input:
[-1,-2,-3,-4]
-3
Except Output:
[0,1]
Examples_C:
Input:
[-3,2,3,5]
0
Except Output:
[0,2]
Hint
使用malloc()函数进行内存分配时应注意分配内存的大小,如
int* cpnums = (int*)malloc((maxn-minn+1) * sizeof(int));
分配(maxn-minn+1)个int的内存单元大小。
Better Solutions:solutions
2017/1/28