[Leetcode questions and Notes] search in rotated sorted Array

Source: Internet
Author: User

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

(I. e .,0 1 2 4 5 6 7Might become4 5 6 7 0 1 2).

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

You may assume no duplicate exists in the array.

 

Problem: Find the target using the binary method.

  1. If a [l] <A [Mid], it indicates that the mid is left ordered and smaller than the mid, as shown in. In this case, if the target is between the L and mid, you need to reset R to mid. In other cases, you need to continue searching on the right end of mid.

2. if a [l]> = A [Mid], the mid is in the right order and all are greater than the mid, as shown in. If the target is between the mid and the R, then you need to reset L to mid. In other cases, you need to continue searching on the left end of mid.

When l + 1 = r, you only need to check whether the elements pointed to by L and R are equal to the target.

The Code is as follows:

 1 public class Solution { 2     public int search(int[] A, int target) { 3         int l = 0; 4         int r = A.length - 1; 5          6         while(l + 1< r){ 7             int mid = l + (r-l)/2; 8             if(A[mid] == target) 9                 return mid;10             if(A[l]< A[mid] ){11                 if(A[mid] >= target && A[l] <= target)12                     r = mid;13                 else {14                     l = mid;15                 }16             }17             else {18                 if(target >= A[mid] && target <= A[r])19                     l = mid;20                 else {21                     r = mid;22                 }23             }24         }25         26         if(target == A[l])27             return l;28         if(target == A[r])29             return r;30         return -1;31     }32 }

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.