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.
Test Instructions:
Suppose that for an ordered array, the implementation uses some kind of transcendental rotation for it, and you don't know
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2 ).
Given a target value, in this array to search for the target value, if found to return the label of the target value, otherwise return-1.
You can assume that there are no duplicate elements in the array.
Algorithm Analysis:
Reference http://pisxw.com/algorithm/Search-in-Rotated-Sorted-Array.html
The problem is still a binary lookup of the deformation, specifically, assuming that the array is a, each time the left edge is L, the right edge is R, and the middle position is M. In each iteration, there are three cases:
(1) If target==a[m], then M is the result we want, direct return;
(2) if A[M]<A[R], then the instructions from M to R must be orderly (not affected by rotate), then we only need to determine whether the target is between M and R, if it is to move the left edge to m+1, otherwise the target in the other half, The right edge is moved to the m-1.
(3) If A[M]>=A[R], then the instructions from L to M must be orderly, also only need to determine whether the target is within this range, the corresponding moving edge can be
AC Code:
<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:12PX;" >public class Solution {public int search (int[] A, int target) { if (a==null| | a.length==0) return-1; int l=0,r=a.length-1; while (l<=r) { int mid= (L+R)/2; if (Target==a[mid]) return mid; if (A[mid]<a[r]) { if (Target>a[mid]&&target<=a[r]) l=mid+1; else r=mid-1; } else { if (Target>=a[l]&&target<a[mid]) r=mid-1; else l=mid+1; } } return-1;} } </span>
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Search in rotated Sorted Array