首页 > ACM题库 > LeetCode > LeetCode-Search in Rotated Sorted Array[数组]
2014
11-18

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.

标签: Array Binary Search
分析

二分查找,难度主要在于左右边界的确定。

代码1

// LeetCode, Search in Rotated Sorted Array
// 时间复杂度O(log n),空间复杂度O(1)
class Solution {
public:
    int search(int A[], int n, int target) {
        int first = 0, last = n;
        while (first != last) {
            const int mid = (first + last) / 2;
            if (A[mid] == target)
                return mid;
            if (A[first] <= A[mid]) {
                if (A[first] <= target && target < A[mid])
                    last = mid;
                else
                    first = mid + 1;
            } else {
                if (A[mid] < target && target <= A[last-1])
                    first = mid + 1;
                else
                    last = mid;
            }
        }
        return -1;
    }
};

Java代码:

public class Solution {
    public static int search(int[] A, int target) {
        return searchBinary(A, 0, A.length-1 , target);
    }

    public static int searchBinary(int A[],int s,int e,int target){
        int mid = (s+e)/2;
        if(A[mid] == target)
            return mid;
        if(s >= e) return -1;
        if( A[mid] < A[e] ){ //后半部分是顺序的
            if(target > A[mid] && target <= A[e]){
                return searchBinary(A, mid+1, e, target);
            }else
                return searchBinary(A, s, mid-1, target);
        }else{ //前半部分顺序的
            if(target >= A[s] && target < A[mid])
                return searchBinary(A, s, mid-1, target);
            else
                return searchBinary(A, mid+1, e, target);
        }

    }
}

相关题目
Search in Rotated Sorted Array II