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.

使用二分搜索需计算l,r 左右边界

1.当A[l] <= A[m]时 说明左半部分已经排好序

2.当A[m] < A[r]时 说明右半部分已经排好序

 

 1 public int search(int[] A, int target) {
 2         int len = A.length;
 3         
 4         // binary search
 5         int l = 0;
 6         int r = len - 1;
 7         while(l <= r){
 8             int m = (l + r) / 2;
 9             if(target == A[m])
10                 return m;
11             
12             // lower is sorted
13             if(A[l] <= A[m]){
14                 if(A[l] <= target && target < A[m])
15                     r = m - 1;
16                 else{
17                     l = m + 1;
18                 }
19             } else {
20                 if(A[m] < target && target <= A[r]){
21                     l = m + 1;
22                 } else{
23                     r = m - 1;
24                 }
25             }
26         }
27         return -1;
28     }

 

 

 

你可能感兴趣的:(LeetCode)