[Classic face question] given an ordered (non-descending) array A, can contain duplicate elements, the minimum I so that a[i] equals target, does not exist return-1

Source: Internet
Author: User

"title"

Given an ordered (non-descending) array A, which can contain duplicate elements, the smallest I makes a[i] equals target, and returns 1 if it does not exist.

"Analysis"

This is where the target first appears in the array. There might be people here who would like to search directly with the original binary, if there is no direct return-1,

If it exists, then the leftmost position that equals the target value interval is found, so that the worst-case complexity is O (n), and does not fully play the two-point lookup advantage.

Please refer to the implementation code and comments for the specific procedure of this solution.

"Code"

/**********************************   Date: 2015-01-05*   sjf0115*   title: Given an ordered (non-descending) array A, which can contain duplicate elements, the smallest I makes a[i] equals target, does not exist returns -1*   blog: **********************************/#include <iostream>using namespace Std;int BinarySearch (int a[],int n,int target) {    if (n <= 0) {        return-1;    } If    int start = 0,end = N-1;    Two-point find variant    while (Start < end) {        int mid = (start + end)/2;        if (A[mid] < target) {            start = mid + 1;        } If        else{            end = mid;        } else    }//while    //target does not exist//    at this time start = end    if (A[start]! = target) {        return-1;    } If    else{        return start;}    } int main () {    int a[] = {2,3,4,4,4,4,4,5,6,7,8};    Cout<<binarysearch (a,11,4) <<endl;    return 0;}


[classic face question] given an ordered (non-descending) array A, can contain duplicate elements, the minimum I so that a[i] equals target, does not exist return-1

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.