Tuesday, October 27, 2015

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.
Solution: binary search, complexity is O(log n), space complexity is O(1).
假设数组是A,每次左边缘为l,右边缘为r,还有中间位置是m。在每次迭代中,分三种情况:
(1)如果target==A[m],那么m就是我们要的结果,直接返回;
(2)如果A[m]<A[r],那么说明从m到r一定是有序的(没有受到rotate的影响),那么我们只需要判断target是不是在m到r之间,如果是则把左边缘移到m+1,否则就target在另一半,即把右边缘移到m-1。
(3)如果A[m]>=A[r],那么说明从l到m一定是有序的,同样只需要判断target是否在这个范围内,相应的移动边缘即可。
public class Solution {
    public int search(int[] A, int target) {
        if(A == null || A.length == 0)
            return -1;
        
        int L = 0, R = A.length - 1;
        while(L <= R) {
            int mid = (L + R) / 2;
            
            if(A[mid] == target)
                return mid;
            
            if(A[L] <= A[mid]) {
                if(target >= A[L] && target <= A[mid])
                    R = mid;
                else
                    L = mid + 1;
            }else {
                if(target <= A[R] && target >= A[mid])
                    L = mid + 1;
                else
                    R = mid;
            }
        }
        return -1;
    }
}

No comments:

Post a Comment