The absolute value of the adjacent element difference is 1, and the target element is found in such an array.

Source: Internet
Author: User

There is such an array A , the size is N , the absolute value of the adjacent element difference is 1 . such as:a={4,5,6,5,6,7,8,9,10,9}. Now, given the a and the target integer t, find t in a position in the. Is there a better way to do it than to traverse it sequentially?

The solution to the problem is very interesting.

The first number of arrays is array[0], the number to find is y, set t = ABS (Y-array[0]). Since the absolute value of each adjacent number difference is 1. So the number before the T position is definitely smaller than y . So go directly to array[t], recalculate t,t = ABS (Y–array[t]), and repeat the above steps. This algorithm mainly uses the difference between the number of the current position and the number of lookups to realize the leap-through search. the efficiency of the algorithm is higher than the algorithm of traversing the array, and it is easy to implement.

void Printfarray (int a[], int n)    {      for (int i = 0; i < n; i++)          printf ("%d", A[i]);      Putchar (' \ n ');    }   int Findnumberinarray (int arr[], int n, int find_number)  {    int next_arrive_index = ABS (find_number-arr[0]); 
   
    while (Next_arrive_index < N)    {      if (arr[next_arrive_index] = = find_number)        return Next_arrive_index ;      Next_arrive_index + = ABS (Find_number-arr[next_arrive_index]);    }    return-1;  }  
   
And this is similar to this topic:

There is an int array, and the difference between each of the two adjacent numbers is either 1 or-1. Now given a number, it is required to find the position of the number in the array.



The absolute value of the adjacent element difference is 1, and the target element is found in such an array.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.