leetcode:search-in-rotated-sorted-array

来源:互联网 发布:sai软件官方下载 编辑:程序博客网 时间:2024/06/14 04:51

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.



Answer:

class Solution {
public:
    int search(int A[], int n, int target) {
        //You may assume no duplicate exists in the array.
        //本题变相考查二分搜索
        int l=0,h=n,m;
        while(l<h){   //区间为左闭右开
            m = l+((h-l)>>1);
            if(A[m]==target)return m;
            if(A[m]>A[l]){  //说明左边有序
                if(target<A[m]&&target>=A[l]){ //搜索左区间,这里用target>=A[l]而非target>A[h-1],可以在没有翻转时,逻辑也是对的
                    h=m;
                }else{ //右区间
                    l=m+1;
                }
            }else{  //说明右边有序
                if(A[m]<target&&target<=A[h-1]){ //搜索右区间
                    l=m+1;
                }else{ //左区间
                    h=m;
                }
            }
        }
        return -1;
    }
};

0 0