Search in rotated Sorted Array

Source: Internet
Author: User

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.

Analysis: Using two-point search method. Mid = (low + high)/2. Consider two scenarios such as:

1. If Nums[low] <= Nums[mid] indicates that the interval is incremented, if the value of target is between the two, then the upper bound is mid-1, otherwise the lower bound is mid + 1;

2. If Nums[low] > Nums[mid] indicates that mid is after the maximum value (example: [4, 5, 6, 0, 1, 2, 3]. Number 0 after 6) If Target is between Nums[mid] and Nums[high], the lower bound is mid + 1; otherwise the upper bound is mid-1.

Run Time 7ms

1 classSolution {2  Public:3     intSearch (vector<int>& Nums,inttarget) {4         if(nums.size () = =0)return-1;5         if(nums.size () = =1){6             if(nums[0] = = target)return 0;7             Else return-1;8         }9         Ten         intLow =0, high = Nums.size ()-1; One          while(Low <=High ) { A             intMid = (low + high)/2; -             if(Nums[mid] = = target)returnmid; -             if(Nums[low] <=Nums[mid]) { the                 if(Nums[low] <= target && target < Nums[mid]) high =mid; -                 ElseLow = mid +1; -             } -             Else{ +                 if(Nums[mid] < target && target <= nums[high]) Low = mid +1; -                 ElseHigh =mid; +             } A         } at         return-1; -     } -};

Search in rotated Sorted Array

Related Article

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.