【leetcode刷题笔记】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.


 

题解:还是按照二分的方法找target。

  1. 如果A[l] < A[mid],说明mid以左有序且都小于mid,如下图所示:这种情况下如果target在l和mid之间,那么需要把r重新置为mid;其他情况都需要到mid右端继续搜索。

     2.如果A[l] >= A[mid], 说明mid以右有序且都大于mid,如下图所示,如果target在mid和r之间,那么需要把l重新置为mid;其他情况都需要到mid左端继续搜索。

当l + 1 = r的时候,只要检查l和r所指向的元素是否等于target即可。

代码如下:

 1 public class Solution {

 2     public int search(int[] A, int target) {

 3         int l = 0;

 4         int r = A.length - 1;

 5         

 6         while(l + 1< r){

 7             int mid = l + (r-l)/2;

 8             if(A[mid] == target)

 9                 return mid;

10             if(A[l]< A[mid] ){

11                 if(A[mid] >= target && A[l] <= target)

12                     r = mid;

13                 else {

14                     l = mid;

15                 }

16             }

17             else {

18                 if(target >= A[mid] && target <= A[r])

19                     l = mid;

20                 else {

21                     r = mid;

22                 }

23             }

24         }

25         

26         if(target == A[l])

27             return l;

28         if(target == A[r])

29             return r;

30         return -1;

31     }

32 }

你可能感兴趣的:(LeetCode)