由于找工作的需要开始刷LeetCode上面的题目,使用的是c语言。水平有限。以后每道题我会先写出我自己的方法,然后学习下大神的方法,并适当的记录下一些思路和想法。
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
//sort nums
int i, j, temp, tempin;
int *result, *index;
index = (int *)malloc(numsSize*sizeof(int));
for (i = 0; i < numsSize; i++)
index[i] = i;
for (i = 1; i < numsSize; i++) {
j = i-1;
temp = nums[i];
tempin = index[i];
while (j >= 0 && nums[j] > temp) {
nums[j+1] = nums[j];
index[j+1] = index[j];
j--;
}
nums[j+1] = temp;
index[j+1] = tempin;
}
for (i = 0; i < numsSize; i++) {
printf("%d %d\n", nums[i], index[i]);
}
j = numsSize-1;
for (i = 0; i < numsSize; i++)
{
while (j > i && (nums[i] + nums[j]) > target) j--;
if (nums[i] + nums[j] == target)
{
result = (int *)malloc(2*sizeof(int));
if (index[i] < index[j]) {
result[0] = index[i] + 1;
result[1] = index[j] + 1;
}
else {
result[0] = index[j] + 1;
result[1] = index[i] + 1;
}
return result;
}
}
}