Search for rotated sorted arrays

Source: Internet
Author: User

It is assumed that an array sorted in ascending order is rotated at a predetermined point in the unknown.

(for example, the array [0,1,2,4,5,6,7] may become [4,5,6,7,0,1,2] ).

Searches for a given target value, returns its index if the target value exists in the array, otherwise returns -1 .

You can assume that there are no duplicate elements in the array.

Your algorithm's time complexity must be O(log n) level.

Example 1:

Input: Nums = [ 4,5,6,7,0,1,2] , target = 0 Output: 4

Example 2:

Input: Nums = [ 4,5,6,7,0,1,2] , target = 3 output:-1

Another binary search for the upgraded version, where I use recursion, if the range is normal ascending, then normal binary lookup, if the range is a rotation sort, then the two sides are searched, if the number on the left is larger than target and the number on the right and target small, then the target is not in the range, return.

The other solution is the fastest use of iterative to do, a simple look at the next, divided into three kinds of situations, later to see the space.

voidBinsearch (int*nums,intLintRintTargetint*index) {    if(l>R)return; if(nums[l]<Nums[r]) {        if(nums[l]>target| | nums[r]<target)return; intMid= (L+R)/2; if(nums[mid]==target) {            *index=mid; return; }        Else if(nums[mid]<target) binsearch (Nums,mid+1, R,target,index); ElseBinsearch (Nums,l,mid-1, Target,index); }    Else    {        if(nums[r]<target&&nums[l]>target)return; intMid= (L+R)/2; if(nums[mid]==target) {            *index=mid; return; }        Else{binsearch (Nums,mid+1, R,target,index); Binsearch (Nums,l,mid-1, Target,index); }    }}intSearchint* Nums,intNumssize,inttarget) {    intindex=-1; Binsearch (Nums,0, numssize-1,target,&index); returnindex;}

Search for rotated sorted arrays

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.