LeetCode 167. 两数之和 II - 输入有序数组-C语言
题目描述
解题思路
暴力解法,通过双层循环遍历整个数组,找出两个数之和等于target的两个位置,返回结果。
代码
int* twoSum(int* numbers, int numbersSize, int target, int* returnSize){
int i, j, flag = 0;
for (i = 0; i < numbersSize - 1; i++) {
for (j = i + 1; j < numbersSize; j++) {
if (numbers[i] + numbers[j] == target){
flag = 1;
break;
}
}
if (flag || numbers[i] > target) {
break;
}
}
*returnSize = 2;
int *res = (int*)malloc(sizeof(int) * 2);
res[0] = i + 1;
res[1] = j + 1;
return res;
}