首页 > 代码库 > [leetcode]Search in Rotated Sorted Array

[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 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.

二分查找的变形

算法思路:

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 begin = 0, end = a.length - 1; 5             while(begin <= end){ 6                 int mid = (begin + end) >> 1; 7                 if(a[mid] == target){ 8                     return mid; 9                 }else if(a[mid] < target){10                     if(a[mid] < a[begin] && target >= a[begin]){11                         end = mid - 1;12                     }else{13                         begin = mid + 1;14                     }15                 }else{16                     if(a[mid] >= a[begin] && target < a[begin]){17                         begin = mid + 1;18                     }else{19                         end = mid - 1;20                     }21                 }22             }23             return -1;24      }25 }