Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e.,0 1 2 4 5 6 7might become4 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.

Have you met this question in a real interview?

Yes

Example

For[4, 5, 1, 2, 3]andtarget=1, return2.

For[4, 5, 1, 2, 3]andtarget=0, return-1.

because the list is rotated. so we need a pivot to know whether the mid and the target are in the same section.

so we can compare the smaller/bigger value between the mid and target with pivot.

if (A[mid] > target && target > pivot) || (A[mid] > target && A[mid] < pivot)

if (A[mid] < target && target < pivot) || (A[mid] < target && A[mid] > pivot)

the above senario the mid and target are in the same increasing section

if (A[mid] > target && A[mid] > pivot && target < pivot) in two different section

if (A[mid] < target && A[mid] < pivot && target > pivot) in two different section

at the end

if (A[mid] == target) or (target == pivot)

can just return the corresponding value

public int search(int[] A, int target) {
        // write your code here
        if (A == null || A.length == 0) {
            return -1;
        }

        int start = 0;
        int end = A.length - 1;

        int pivot = A[end];

        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (A[mid] == target) {
                return mid;
            } else if (A[mid] > target && target > pivot) {
                end = mid;
            } else if (A[mid] > target && A[mid] < pivot) {
                end = mid;
            } else if (A[mid] > target && target < pivot) {
                start = mid;
            } else if (A[mid] < target && target < pivot) {
                start = mid;
            } else if (A[mid] < target && A[mid] > pivot) {
                start = mid;
            } else if (A[mid] < target && target > pivot) {
                end = mid;
            } else if (target == pivot) {
                return A.length - 1;
            }
        }

        if (A[start] == target) {
            return start;
        } else if (A[end] == target) {
            return end;
        }

        return -1;

    }

results matching ""

    No results matching ""