/*
给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。
你需要实现的函数twoSum需要返回这两个数的下标
例:
给出 numbers = [15, 2, 7, 11], target = 9, 返回 [1, 2].
*/
public class Demo05 {
public static void main(String[] args) {
int[] A ={-1,-2,-3,-4,-5,-6,-100,-98,-111,-11};
TwoSum(A,-111);
}
public static int[] TwoSum(int[] numbers, int target){
int x =0;
int[] count =new int[2];
while (x<=numbers.length-2) { //可进行的最后一轮比较为轮数为最后俩数的比较,即数组长度-1,因为x =0;所以-2
for (int i = x + 1; i < numbers.length; i++) {
if (target - numbers[x] == numbers[i]) {
count[0] = x;
count[1] = i;
System.out.println(x + "," + i);
} else {
continue;
}
}
x++;
}
return count;
}
}
1、先弄明白俩数和所求和之间的关系
注意:
2、弄明白嵌套循环各个循环的次数,否则容易报错,或其求出的数据不满足要求