leetcode 81. 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.

解析

class Solution {
    public boolean search(int[] a, int target) {
        if (a.length == 0 || a== null)
            return false;
        int lo = 0, hi = a.length - 1;
        while (lo < hi) {
            int mid = (lo + hi) >> 1;
            if (a[mid] == target) {
                return true;
            } else if (a[mid] > a[hi]) {
                //考虑单调的一边
                if (a[mid] > target && target >= a[lo]) {
                    hi = mid;
                } else {
                    lo = mid + 1;
                }
            } else if (a[mid] < a[hi]) {
                if (a[mid] < target && a[hi] >= target) {
                    lo = mid + 1;
                } else {
                    hi = mid;
                }
            } else {
                hi--;
            }
        }
        return a[lo] == target ? true : false;
    }
}

你可能感兴趣的:(LeetCode,array,java)