LintCode: Search in Rotated Sorted Array

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LintCode: 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.

public class Solution {
    /** 
     *@param A : an integer rotated sorted array
     *@param target :  an integer to be searched
     *return : an integer
     */
    public int search(int[] A, int target) {
        // write your code here
        // handle corner case
        if (A == null || A.length == 0) {
            return -1;
        }
        
        // find the break point
        int start = 0, end = A.length - 1;
        int element = A[end];
        int point = 0;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            int current = A[mid];
            if (current < element) {
                end = mid;
            } else {
                start = mid;
            }
        }
        if (A[start] < element) {
            point = start;
        } else {
            point = end;
        }
        
        if (A[point] == target) {
            return point;
        }
        end = A.length - 1;
        // decide which part to search
        if (target <= A[end]) {
            start = point + 1;
        } else {
            start = 0;
            end = point - 1;
        }
        // begin binary search
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            int current = A[mid];
            if (target > current) {
                start = mid;
            } else if (target < current){
                end = mid;
            } else {
                return mid;
            }
        }
        if (A[start] == target) {
            return start;
        }
        if (A[end] == target) {
            return end;
        }
        return -1;
    }
}

The trick here is to find the break point first, then to search the element, both use binary search

以上是关于LintCode: Search in Rotated Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

lintcode-medium-Search in Rotated Sorted Array

lintcode-medium-Search in Rotated Sorted Array II

Lintcode011.Search Range in Binary Search Tree

lintcode-easy-Insert Node in a Binary Search Tree

[LintCode] Search in Rotated Sorted Array

Lintcode062.Search in Rotated Sorted Array