Topic
The size of any two adjacent elements in array a differs by 1, and is given the array A and target integer t to find the position of T in array A. Arrays: [1,2,3,4,3,4,5,6,5], locate 4 in the array.
Ideas
The worst-time complexity of the problem is also O (N), so the focus is on finding a way to reduce the number of comparisons as much as possible.
Arrays: [1,2,3,4,3,4,5,6,5], locate 4 in the array. 4 and 1 Compare, the difference is 3, so even if the best case (increment or decrement), 4 is in a[3] position, you can skip a[1]a[2]. This may save time if a particular array (target value and a[1) is quite different.
So the rule: for the target T, starting from the current position a[i] comparison, the next possible position is I = ABS (A[I]-T)
Code
/* ---------------------------------------------* Date: 2015-02-19 * SJF0115 * Title: Adjacent element Difference 1, looking for target integer T * Source: * Blog:-----------------------------------------------*/ #include <iostream> #include <algorithm> using namespace STD;classSolution { Public:intFind (intNum[],intNintTarget) {if(N <=0){return-1; }//if for(inti =0; i < n;) {if(Num[i] = = target) {returnI }//ifi + =ABS(Num[i]-target); }//for return-1; } };intMain () {solution solution;intNum[] = {1,2,3,2,3,4,3,2,3};inttarget =4;cout<<solution. Find (NUM,9, target) <<endl; }
Above just return to the first target location, if the title asks to return all target location codes as follows:
/* ---------------------------------------------* Date: 2015-02-19 * SJF0115 * Title: Adjacent element Difference 1, looking for target integer T * Source: * Blog:-----------------------------------------------*/ #include <iostream> #include <vector> #include <algorithm> using namespace STD;classSolution { Public: vector<int>Find (intNum[],intNintTarget) { vector<int>Resultif(N <=0){returnResult }//if for(inti =0; i < n;) {if(Num[i] = = target) {Result.push_back (i); i + =2; }//if Else{i + =ABS(Num[i]-target); } }//for returnResult } };intMain () {solution solution;intNum[] = {1,2,3,4,3,4,3,2,3,2,3,4};inttarget =4; vector<int>result = solution. Find (NUM, A, target); for(inti =0; i < result.size (); ++i) {cout<<result[i]<<endl; }//for}
[Classic face question] [Baidu] The size of any two adjacent elements in array a differs by 1, in which a number is found.