leetcode---search-in-rotated-sorted-array---查找

来源:互联网 发布:中国向何处去 知乎 编辑:程序博客网 时间:2024/05/22 13:48

题目描述

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.

class Solution {public:    int search(int A[], int n, int target)     {        int l = 0;        int h = n-1;        while(l <= h)        {            int m = (l + h) / 2;            if(A[m] == target)                return m;            else if(A[m] <= A[h])            {                if(A[m] < target && target <= A[h])                    l = m + 1;                else                    h = m - 1;            }            else            {                if(A[m] > target && target >= A[l])                    h = m - 1;                else                    l = m + 1;            }        }        return -1;    }};
原创粉丝点击