[leetcode]Search in Rotated Sorted Array
Search in Rotated Sorted Array
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e.,
0 1 2 4 5 6 7
might 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.
二分查找的变形
算法思路:
a[mid] == target return mid;
a[mid] < target 分为两种情况
1. a[mid]和target在同半边,begin = mid + 1
2. a[mid]和target在不同的半边,则a[mid]肯定在后面,target在前半边,因此往前找end = mid - 1;
a[mid] > target同理
1. a[mid]和target在同半边,end = mid - 1;
2. a[mid]和target在不同的半边,则a[mid]肯定在前面,target在后半边,因此往前找begin = mid + 1;
代码如下:
1 public class Solution { 2 public int search(int[] a, int target) { 3 if(a == null || a.length == 0) return -1; 4 int length = a.length; 5 int begin = 0, end = length - 1; 6 while(begin <= end){ 7 int mid = (begin + end) >> 1; 8 if(a[mid] == target){ 9 return mid; 10 }else if(a[mid] > target){ 11 if(target < a[begin] && a[mid] >= a[begin]){//这里如果写成a[mid]<=a[end]就不行了,因为a[mid]<=a[end]不能保证在前半段 12 begin = mid + 1; 13 }else{ 14 end = mid - 1; 15 } 16 }else{ 17 if(a[mid] < a[begin] && target >= a[begin]){ 18 end = mid - 1; 19 }else{ 20 begin = mid + 1; 21 } 22 } 23 } 24 return -1; 25 } 26 }