lintcode-medium-Search in Rotated Sorted Array

Posted 哥布林工程师

tags:

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

 

Example

For [4, 5, 1, 2, 3] and target=1, return 2.

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

Challenge

O(logN) time

 

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
        
        if(A == null || A.length == 0)
            return -1;
        
        int left = 0;
        int right = A.length - 1;
        
        return search(A, target, left, right);
    }
    
    public int search(int[] A, int target, int left, int right){
        
        if(left > right)
            return -1;
        
        if(left == right){
            if(A[left] == target)
                return left;
            else
                return -1;
        }
        
        int mid = left + (right - left) / 2;
        
        if(A[mid] == target)
            return mid;
            
        if(A[mid] > target){
            if(A[mid] > A[left]){
                int index1 = search(A, target, left, mid - 1);
                int index2 = search(A, target, mid + 1, right);
                    
                if(index1 == -1 && index2 == -1)
                    return -1;
                else if(index1 == -1)
                    return index2;
                else
                    return index1;
            }
            else{
                return search(A, target, left, mid - 1);
            }
        }
        else{
            if(A[mid] > A[left]){
                return search(A, target, mid + 1, right);
            }
            else{
                int index1 = search(A, target, left, mid - 1);
                int index2 = search(A, target, mid + 1, right);
                    
                if(index1 == -1 && index2 == -1)
                    return -1;
                else if(index1 == -1)
                    return index2;
                else
                    return index1;
            }
        }
        
    }
    
}

 

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

12.Python操作关系型数据库

sql 语句中in ,not in

in memory 和 in the memory

IN610/IN610L/IN612替代NRF52832/NRF52840

in的用法归纳总结

/usr/include/netinet/in.h:138:注意:候选人是:in_addr& in_addr::operator=(const in_addr&)