Search in Rotated Sorted Array II

来源:互联网 发布:轮胎动平衡三个数据 编辑:程序博客网 时间:2024/06/08 10:19

 Search in Rotated Sorted Array II

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Suppose an array sorted in ascending order 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).

Write a function to determine if a given target is in the array.

The array may contain duplicates.

Subscribe to see which companies asked this question.

解析:

分情况考虑,由于有重复的数字,这个比较复杂,直接right--也能过。


代码:

class Solution {public:    int search(vector<int>& nums, int target) {        if (nums.empty())        return false;        int left=0;        int right=nums.size()-1;        while(left<right)        {            int mid=(left+right)/2;            if (target==nums[mid])            return true;                        if (target>nums[mid])            {               if (nums[mid]>nums[right])               {                   left=mid+1;               }               else if (nums[mid]<nums[right])               {                   if (target<=nums[right])                   {                       left=mid+1;                   }                   else                   {                       right=mid-1;                   }               }                             else               {                   right--;               }                            }            if (target<nums[mid])            {               if (nums[mid]<nums[right])               {                   right=mid-1;               }               else if (nums[mid]>nums[right])               {                   if (target>=nums[left])                   {                       right=mid-1;                   }                   else                    {                       left=mid+1;                   }               }              else              {                  right--;              }            }        }        if (left>right) return false;        if (nums[left]==target) return true;        return false;            }};



0 0
原创粉丝点击