zoukankan      html  css  js  c++  java
  • LeetCode-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.

    class Solution {
    public:
        int FindRot(int A[],int start,int end){
            if(start==end-1){
                //two
                if(A[start]>A[end])return start;
                else return -1;
            }
            else{
                int mid=(start+end)/2;
                if(A[mid]<A[end])return FindRot(A,start,mid);
                else return FindRot(A,mid,end);
            }
        }
        int searchBinary(int A[],int start,int end,int target){
            if(start>end){
                return -1;
            }
            else{
                int mid=(start+end)/2;
                if(target>A[mid])return searchBinary(A,mid+1,end,target);
                else if(target==A[mid])return mid;
                else return searchBinary(A,start,mid-1,target);
            }
        }
        int search(int A[], int n, int target) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if(n==0)return -1;
            if(n==1){
                if(A[0]==target)return 0;
                else return -1;
            }
            if(A[0]<A[n-1]){
                //no rotate
                return searchBinary(A,0,n-1,target);
            }
            else{
                int index=FindRot(A,0,n-1);
                int i1=searchBinary(A,0,index,target);
                int i2=searchBinary(A,index+1,n-1,target);
                if(i1!=-1)return i1;
                if(i2!=-1)return i2;
                return -1;
            }
        }
    };
    
  • 相关阅读:
    Python multiprocessing相关疑问
    Tornado demo3
    WebSockets
    Tornado Demo1---webspider分析
    Python assert断言
    Python学习之--数据基础
    Python学习之--python概要
    Python学习之--函数/生成器/装饰器
    Python学习之文件操作
    Python操作MySQL数据库
  • 原文地址:https://www.cnblogs.com/superzrx/p/3326394.html
Copyright © 2011-2022 走看看