搜索旋转排序数组Ⅱ(二分查找)

 二分查找中确定左右边界很重要,利用 first和mid对应的数据,target分别和first,mid的对应的数据关系共四种,其中只有一种能够准确判断出目标数据应该存在的范围

由于本道题目允许数组中出现重复的数据,可以做如下操作:

如果

A[m]>A[1],则区间[1~m]一定自增

A[m]==A[1]确定不了,那就1++,继续往下看

class Solution {
    public boolean search(int[] A, int target) {
    int first = 0, last = A.length;
    while (first != last)
    {
     int mid = (first + last) / 2;
        if (A[mid] == target)
            return true;
        if (A[first] < A[mid])
    
            if (A[first] <= target&&target < A[mid])
                last = mid;
            else first = mid + 1;
    
        else if (A[first] > A[mid])
        
            if (A[mid]<target&&target<=A[last-1])
                first = mid + 1;
            else last = mid;
        
        else//skip duplicate one
            //A[first]==A[mid]
            first++;
    }
    return false;
    }
}
原文地址:https://www.cnblogs.com/ywqtro/p/12469517.html