1. 题目
2. 解答
遍历数组元素之和,由于只有唯一答案,并且数组中同一个元素不能重复出现,
因此可以使用双重遍历方式来计算所有可能;
#include <stdio.h>
void solve(int num[], int len, int target)
{
for (int i = 0; i < len - 1; i++) {
for (int j = i+ 1; j < len; j++) {
if (target == num[i] + num[j]) {
printf("[%d,%d]\n", i, j);
}
}
}
}
int main()
{
int target;
int len;
scanf("%d %d", &target, &len);
int num[len];
for (int i = 0; i < len; i++) {
scanf("%d", &num[i]);
}
solve(num, len, target);
return 0;
}
输出:
-G3-3579:~/data/source/leetcode$ gcc 1.c
G3-3579:~/data/source/leetcode$ ./a.out
9 4
2 7 11 15
[0,1]
G3-3579:~/data/source/leetcode$ ./a.out
6 3
3 2 4
[1,2]
G3-3579:~/data/source/leetcode$ ./a.out
6 2
3 3
[0,1]