一组数中是否存在若干数之和等于已知数
1.是否存在两个数的和与已知数(key)相等。
A:穷举:在数组中任选两个数,判断是否等于已知数,复杂度O(N^2).
B:二分:先排序(若是有序,则不需要),然后二分查找M-array[i]是否存在于这个数组,复杂度O(N*log(N)).
C:先排序(若是有序,则不需要),然后用两个指针(头指针head与尾指针tail),当*head+*tail>key,则tail--,若是小于,则是head++,若是相等,则是存在。
对于C:
int getResult(int *num, int n_len, int key, int &num_1, int &num_2) {
int *i, *j;
int temp;
i = num, j = num + n_len - 1;
while (i < j) {
temp = *i + *j;
if (temp > key) {
j--;
} else if (temp < key) {
i++;
} else {
num_1 = *i;
num_2 = *j;
return true;
}
}
return false;
}
public static void getResult(int[] num_Array, int len, int key) {
int i, j, temp;
i = 0;
j = len - 1;
while (i < j) {
temp = num_Array[i] + num_Array[j];
if (temp > key) {
j--;
} else if (temp < key) {
i++;
} else {
System.out.println(num_Array[i] + " " + num_Array[j]);
return;
}
}
}

浙公网安备 33010602011771号