1. 程式人生 > 實用技巧 >求一個數組中兩個陣列之和滿足給定值,並輸出滿足要求的兩個資料的位置

求一個數組中兩個陣列之和滿足給定值,並輸出滿足要求的兩個資料的位置

/*
給一個整數陣列,找到兩個數使得他們的和等於一個給定的數 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、弄明白巢狀迴圈各個迴圈的次數,否則容易報錯,或其求出的資料不滿足要求