Tuesday, November 25, 2014

Search in Rotated Sorted Array

[解题思想]
同样是二分,难度主要在于左右边界的确定。需要结合两个不等式:
1. A[middle] ? A[left]
2. A[middle] ? target

   int search(int A[], int n, int target) {
        int i = 0, j = n - 1;
        while (i <= j)
        {
            int mid = (i + j) / 2;
            if (A[mid] == target)
                return mid;
            if (A[i] <= A[mid])
            {
                if (A[i] <= target && target < A[mid])
                    j = mid - 1;
                else
                    i = mid + 1;
            }
            else
            {
                if (A[mid] < target && target <= A[j])
                    i = mid + 1;
                else
                    j = mid - 1;
            }
        }
        return -1;
    }

No comments:

Post a Comment