码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】Search in Rotated Sorted Array II

时间:2017-12-13 11:34:37      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:last   lex   hat   follow   --   eterm   mil   tar   pos   

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.

int BinarySearch2(int *arr,int len,int target)
{
    int first = 0,last = len,mid = 0;

    while(first <= last)
    {
        mid = (last - first)/2 + first;
        if(arr[mid] == target) return mid;
        if(arr[mid] > arr[last - 1])
        {
            if(target >= arr[first] && target < arr[mid])
                last = mid;
            else
                first = mid + 1;
        }
        else if(arr[mid] == arr[last - 1]) last--;
        else
        {
            if(target <= arr[last - 1] && target > arr[mid])
                first = mid + 1;
            else
                last = mid;
        }
    }
    return -1;
}

  

【LeetCode】Search in Rotated Sorted Array II

标签:last   lex   hat   follow   --   eterm   mil   tar   pos   

原文地址:http://www.cnblogs.com/hatsusakana/p/8031444.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!