81. Search in Rotated Sorted Array II

来源:互联网 发布:底盘弹簧增高垫淘宝 编辑:程序博客网 时间:2024/06/06 05:43

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.

方法整体上与“Search in Rotated Sorted Array”相同,处理相等的地方需要调整一下,时间复杂度最坏为O(n),如[1, 1, 1, 1, 1, 1, 1, 1, 1, 3],查找数值3的时候,程序如下所示:

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