I. Source and description of the problem
Today saw July's microblog, found the July problem, there is this problem, very interesting.
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.
two. Algorithm analysis and implementation
the worst time complexity of the topic is also O (N) (increment or decrement), 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).
public class Solution {public static vector<integer> ve = new vector<integer> (); public static void Find (int num[], int n, int target) { if (n <= 0) return; for (int i = 0; i < n;) { if (num[i] = = target) { ve.add (i); i + = 2; } else i + = Math.Abs (Num[i]-target); } return; } public static void Main (String args[]) { ve.clear (); int num[] = {1, 2, 3, 2, 3, 4, 3, 2, 3}; int target = 4; Find (num, num.length, target); for (int i:ve) System.out.println (i + "");} }
Why +2? such as "4,3,4". +1 certainly not.
[Baidu] Array A of any two adjacent element size difference 1, in which to find a number