#63 Search in Rotated Sorted Array II

本文介绍了一种解决含有重复元素的旋转排序数组搜索问题的方法。通过调整二分查找算法,先定位最小值索引,再进行目标值搜索。文章提供了一个通过实际测试案例验证的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

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.

Example

Given [1, 1, 0, 1, 1, 1] and target = 0, return true.
Given [1, 1, 1, 1, 1, 1] and target = 0, return false.

题目思路:

这题和#62一样,不同的是数组中可能有重复数字出现。所以在第一次寻找最小值的index时,我先把A[l] == A[l + 1]和A[r] == A[r - 1]的情况过滤掉,再用binary search找最小值的位置。

Mycode(AC = 50ms):

class Solution {
    /** 
     * param A : an integer ratated sorted array and duplicates are allowed
     * param target :  an integer to be search
     * return : a boolean 
     */
public:
    bool search(vector<int> &A, int target) {
        // write your code here
        if (A.size() == 0) return false;
        
        // find index of minimum number in A
        int l = 0, r = A.size() - 1, sidx = -1;
        while (l + 1 < r) {
            while (l + 1 < r && A[l] == A[l + 1]) {
                l++;
            }
            
            while (l + 1 < r && A[r] == A[r - 1]) {
                r--;
            }
            
            int mid = (l + r) / 2;
            
            if (A[mid] <= A[l] || A[mid] <= A[r]) {
                r = mid;
            }
            else {
                l = mid;
            }
            
            //cout << l << " " << r << endl;
        }
        sidx = A[l] <= A[r]? l : r;
        
        // get normally sorted numbers indexed from
        // start ~ end
        int start = sidx, end = sidx + A.size() - 1;
        while (start <= end) {
            int mid = (start + end) / 2;
            
            if (A[mid % A.size()] == target) {
                return true;
            }
            else if (A[mid % A.size()] < target) {
                start = mid + 1;
            }
            else {
                end = mid - 1;
            }

        }
        
        return false;
        
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值