在笔试中遇到过这样一个数组问题,只知道一般的解法:
数组第一个数为array[0], 要找的数为y,设t = abs(y - array[0])。由于每个相邻的数字之差的绝对值为1。故第t个位置之前的数肯定都比y小。因此直接定位到array[t],重新计算t,t = abs(y – array[t]),再重复上述步骤即可。这种算法主要利用了当前位置的数与查找数的差来实现跨越式搜索。算法效率要比遍历数组的算法要高一些,并且易于实现。
代码如下所示:
#include <iostream>
using namespace std;
int search(int *A, int n, int t);
int main() {
int n;
int A[100];
cin >> n;
for (int i = 0; i < n; i++) {
cin >> A[i];
}
for (int i = 0; i < n; i++) {
cout << search(A, n, A[i]);
}
}
/*
t为目标
*/
int search(int *A, int n, int t) {
int temp = abs(t - A[0]);
while (temp < n) {
if (t == A[temp]) {
return temp;
}
else {
temp = temp + abs(t - A[temp]);
}
}
return -1;
}