[C++]LeetCode: 44 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?

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

思路:同《Search in Rotated Sorted Array》类似,唯一区别就在当A[START] == A[MID]的处理

复杂度: 当有重复数字,最差的情况是O(N)

解析:A[START] == A[MID]需要全局搜索,逐一移动START. 因为无法判断哪一边是按顺序排列的。

To explain why, consider this sorted array 1111115, which is rotated to 1151111.

Assume left = 0 and mid = 3, and the target we want to search for is 5. Therefore, the condition A[left] == A[mid] holds true, which leaves us with only two possibilities:

  1. All numbers between A[left] and A[right] are all 1's.
  2. Different numbers (including our target) may exist between A[left] and A[right].

As we cannot determine which of the above is true, the best we can do is to move left one step to the right and repeat the process again. Therefore, we are able to construct a worst case input which runs in O(n), for example: the input 11111111...115.

AC Code:

class Solution {
public:
    bool search(int A[], int n, int target) {
        //这次数组中可能有重复数字
        
        int start = 0;
        int end = n - 1;
        
        while(start <= end)
        {
            //防止溢出
            int mid = start + (end - start) / 2;
            if(A[mid] == target) return true;
            if(A[start] < A[mid])
            {
                if(A[start] <= target && target <= A[mid])
                {
                    end = mid - 1;
                }
                else
                {
                    start = mid + 1;
                }
            }
            else if(A[start] > A[mid])
            {
                
                if(A[mid] <= target && target <= A[end])
                {
                    start = mid + 1;
                }
                else
                {
                    end = mid - 1;
                }
            }
            else
                start++;
        }
        
        return false;
        
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值