leetcode 81 Search in Rotated Sorted Array II ----- java

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.

第33题的延伸题。

33题说的是给定一个数组,这个数组可能从某个位置分成两部分,这两部分都是排序好的,假设没有重复的数字,给定一个数,然后求出那么数的位置,不存在则返回-1;

这道题说的就是假设可以重复。

当然不能直接循环一次,那样就没有意义了。

如果没有重复的数字,就修改一下二分法就行了,其实也就是几种情况,分类讨论一下就好。

在这里有重复的数字,那么就是,如果遇到pos和left处的数字一样,或者说pos和right处的数字一样,那么移动一个数字。

public class Solution {
    public boolean search(int[] nums, int target) {
        int len = nums.length;
        int left = 0,right = len-1;
        int pos;
        while( left <= right ){
            pos = (left+right)/2;
            if( target == nums[pos])
                return true;
            else if( nums[pos] > nums[left] ){
                if( target >= nums[left] && target < nums[pos])
                    right = pos-1;
                else
                    left = pos+1;
            }else if( nums[pos] < nums[right] ){
                if( target <= nums[right] && target > nums[pos])
                    left = pos+1;
                else
                    right = pos-1;
            }else if( nums[pos] == nums[left] ){
                left++;
            }else if( nums[pos] == nums[right] )
                right--;
        }
        return false;
            
    }
}
原文地址:https://www.cnblogs.com/xiaoba1203/p/5967285.html