一种快速找数的方法

今天看一个博客看到一中找数的方法,感觉很有意思,就自己理解了下然后写了份代码...

题目的意思是这样的:对一个相邻元素的差的绝对值都为1的一个数组,找出某个元素是否在其中出现过,若出现过的话打印它的一个下标,否则提示没找到。

我们先来理解下,首先,相邻元素的差的绝对值为1,那么某个元素 n 和第一个元素 array[0] 的下标的差不大于 index = |n - array[0]|,如果下标位置index没找到元素,那么继续 index += |n - array[index]|,也就是从原index继续向下|n - array[index]|个位置,因为此时 n 和 array[index]的位置差最少也为|n - array[index]|。如此下去最终可以找到元素。这样就可以跳跃性地去查找元素而不是一个一个遍历。但这里要注意的是,相邻元素之差的绝对值应该为1.最起码来说不能大于1,可以为0,但是为0的话这个算法的效果就没那么明显了。

下面是程序:

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <cmath>
 4 
 5 using namespace std;
 6 
 7 int findNumber(int* arrayL, int len, int numberToFind) {
 8     int index = abs(numberToFind - arrayL[0]);
 9     
10     //如果没找到就继续下一个遍历
11     while (index < len) {
12         if (arrayL[index] == numberToFind)
13             return index;
14 
15         index += abs(numberToFind - arrayL[index]);
16     }
17     //代表没有找到
18     return -1;
19 }
20 
21 int main(int argc, char const *argv[])
22 {
23     int lenOfArray;
24     int* arrayL;
25 
26     printf("Enter the length of the array: ");
27     scanf("%d", &lenOfArray);
28 
29     arrayL = new int[lenOfArray];
30     printf("Enter the elements of the array: ");
31     for (int i = 0; i != lenOfArray; i++)
32         scanf("%d", &arrayL[i]);
33 
34     int numberToFind;
35     printf("Do you want to find a number<Y, N>? ");
36     char command;
37     while (scanf("
%c", &command) && 
38                 (command != 'n' && command != 'N')) {
39         printf("Enter the number you want to find: ");
40         scanf("%d", &numberToFind);
41 
42         printf("The index of the number you want to find: %d
",
43                      findNumber(arrayL, lenOfArray, numberToFind));
44 
45         printf("find another number?<Y, N> ");
46     }
47 
48     delete []arrayL;
49     return 0;
50 }
原文地址:https://www.cnblogs.com/xiezhw3/p/3442510.html