[Baidu] Array A of any two adjacent element size difference 1, in which to find a number

Source: Internet
Author: User

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

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.