题解 | #两数之和#我写错了,不过感觉删了很可惜
两数之和
https://www.nowcoder.com/practice/20ef0972485e41019e39543e8e895b7f
写到最后我才发现我已经把原数组搞乱了,不过开头复制原数组还可以写,不过就太麻烦了;
我一开始没有想到哈希表,我先使用快排,再用二分查找完成,结果返回的下标是快排完的下标,最后我才注意到,戒之!
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param numbers int整型一维数组 * @param numbersLen int numbers数组长度 * @param target int整型 * @return int整型一维数组 * @return int* returnSize 返回数组行数 */ #include <stdlib.h> int cmp(const void *e1,const void *e2){ return *(int *)e1 - *(int *)e2; } int bisearch(int *numbers ,int target ,int numbersLen){ int head = 0; int tail = numbersLen - 1; int mid = 0; while(head <= tail){ mid = (head + tail) / 2; if(numbers[mid] == target) return mid; else if(numbers[mid] > target) tail = mid - 1; else if(numbers[mid] < target) head = mid + 1; } return -1; } int* twoSum(int* numbers, int numbersLen, int target, int* returnSize ) { int *res = (int *)malloc(sizeof(int)*2); int temp = 0; qsort(numbers, numbersLen, sizeof(int), cmp); for(int i = 0;i < numbersLen;i++){ temp = bisearch(numbers, target-numbers[i], numbersLen); if((temp > 0)&&(temp != i)){ res[0] = i+1; res[1] = temp +1; *returnSize = 2; return res; } } *returnSize = 2; return NULL; }