阿牧路泽

哪有那么多坚强,无非是死扛罢了
  博客园  :: 首页  :: 新随笔  :: 联系 :: 管理

7、【常见算法】数组元素查找

Posted on 2018-10-16 09:42  阿牧路泽  阅读(288)  评论(0编辑  收藏  举报

  题目:有这样一个数组A,大小为n,相邻元素差的绝对值都是1。如:A={4,5,6,5,6,7,8,9,10,9}。现在,给定A和目标整数t,请找到t在A中的位置。除了依次遍历,还有更好的方法么?

  解法:数组第一个数为array[0], 要找的数为y,设t = abs(y - array[0])。由于每个相邻的数字之差的绝对值为1。故第t个位置之前的数肯定都比y小。因此直接定位到array[t],重新计算t,t = abs(y – array[t]),再重复上述步骤即可。这种算法主要利用了当前位置的数与查找数的差来实现跨越式搜索。算法效率要比遍历数组的算法要高一些,并且易于实现。

 1 //数组元素查找
 2 #include <iostream>
 3 #include <cmath>
 4 
 5 using namespace std;
 6 
 7 typedef int Index;
 8 
 9 int findNum(int *arr, int len, int target)
10 {
11     if(!arr || len < 0)
12         cout << "Invalid Input!" << endl;
13     Index iter = abs(arr[0] - target);
14     while(iter < len)
15     {
16         if(arr[iter] == target)
17             return iter;
18         iter += abs(arr[iter] - target);
19     }
20     return -1;
21 }
22 
23 void printArray(int *arr, int len)
24 {
25     if(!arr || len < 0)
26         cout << "Invalid Input" << endl;
27     for(Index iter = 0; iter < len; iter++)
28     {
29         cout << arr[iter] << endl;
30     }
31 }
32 
33 int main()
34 {
35     const int arrMax = 10;
36     int arr[arrMax] = {4, 5, 6, 5, 6, 7, 8, 9, 10, 9};
37     printArray(arr, arrMax);
38 
39     int target = 7;
40     cout << target << "在数组中的索引为:";
41     cout << findNum(arr, arrMax, target) << endl;
42 
43     target = 11;
44     cout << target << "在数组中的索引为:";
45     cout << findNum(arr, arrMax, target) << endl;
46 
47 //    system("pause");
48     return 0;
49 }