leetcode81---Search in Rotated Sorted Array II

来源:互联网 发布:新歌声第二季网络战队 编辑:程序博客网 时间:2024/06/06 12:52

问题描述:

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.

特点:含有重复数字。如[1,3,1,1,1] 3这种情况。

问题求解:

class Solution {public:    bool search(vector<int>& nums, int target) {        int n=nums.size();        if(n==0) return false;        int low=0, high=n-1, mid;        while(low<=high)        {            mid=(low+high)/2;            if(nums[mid]==target) return true;            else if(nums[low] < nums[mid])            {                if(target<nums[mid] && target>=nums[low])                {                    high=mid-1;                }                else                {                    low=mid+1;                }            }            else if(nums[low] > nums[mid])            {                if(target<=nums[high] && target>nums[mid])                {                    low=mid+1;                }                else                {                    high=mid-1;                }            }            else//如[1,3,1,1,1] 3这种情况            {//nums[low] == nums[mid]                low++;            }        }        return false;    }};
0 0
原创粉丝点击