Search in Rotated Sorted Array

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

Search in Rotated Sorted Array
 1 public class Solution {
 2     //all is equal in sorted array
 3     public int search(int[] A, int target) {
 4         if(A.length<=0) return -1;
 5         int start =0,end =A.length-1;
 6         while(start<=end){
 7             int mid = (start+end)/2;
 8             if(A[mid]==target) return mid;
 9             if(A[mid]>=A[start]){//don‘t forget the equal
10                 if(target<=A[mid] && target>=A[start]){
11                     end = mid-1;
12                 }
13                 else{
14                     start = mid+1;
15                 }
16             }
17             else{
18                 if(target>=A[mid] && target<=A[end]){
19                     start = mid+1;
20                 }
21                 else{
22                     end = mid-1;
23                 }
24             }
25         }
26         return -1;
27     }
28 }
View Code

Search in Rotated Sorted Array

上一篇:Convert Sorted Array to Binary Search Tree


下一篇:Path Sum