标签:
Suppose a sorted array is rotated at 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 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.
对于这道题,最开始直接线性搜索竟然通过了,但自己感觉过意不去
之后尝试用二分查找法,
1 public int search(int[] A, int target) { 2 return this.binarySearch(A, target, 0, A.length-1); 3 } 4 private int binarySearch(int[]A,int target,int low,int hi){ 5 while(low<=hi){ 6 int mid=(low+hi)/2; 7 if(target==A[mid]) return mid; 8 if(A[low]>A[mid]){ 9 if(target>A[mid]&&target<A[hi]){ 10 low=mid+1; 11 } else{ 12 hi=mid-1; 13 } 14 }else{ 15 if(target<A[mid]&&target>A[low]){ 16 hi=mid-1; 17 }else{ 18 low=mid+1; 19 } 20 } 21 } 22 return -1; 23 }
Leetcode Search in Rotated Sorted Array
标签:
原文地址:http://www.cnblogs.com/criseRabbit/p/4267754.html