"Search in rotated Sorted Array" cpp

Source: Internet
Author: User

title :

Suppose a sorted array is rotated on some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2 ).

You is given a target value to search. If found in the array is return its index, otherwise return-1.

Assume no duplicate exists in the array.

Code :

classSolution { Public:    intSearchintA[],intNinttarget) {        intBegin =0; intEnd = N1;  while(Begin! =end) {            if(begin+1==end) {                if(A[begin]==target)returnbegin; if(A[end]==target)returnend; return-1; }            Const intMid = (end+begin)/2; if(A[mid]==target)returnmid; if(target<A[mid]) {                if(a[begin]<A[mid]) {                    if(target>=A[begin]) {End= mid-1; }                    Else{begin= mid+1; }                }                Else{End= mid-1; }            }            Else            {                if(a[begin]<A[mid]) {Begin= mid+1; }                Else                {                    if(target<=A[end]) {Begin= mid+1; }                    Else{End= mid-1; }                }            }        }        if(A[begin]==target)returnbegin; return-1; }};

Tips:

1. The size of target and A[mid] is discussed first

2. Because at least one of the first half or the second half is orderly, and then according to this to sub-condition discussion

There are some logic in the if else code that can be combined, but keeping the original logic in mind is easier to understand, preserving the status quo.

"Search in rotated Sorted Array" cpp

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.