81. Search in Rotated Sorted Array II

Posted CodesKiller

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

此题受到了Search in Rotated Sorted Array以及Find Minimum in Rotated Sorted Array2的启发,两者结合起来做就可以了,代码如下:

public class Solution {

    public boolean search(int[] nums, int target) {

        if(nums.length==0) return false;

        int left = 0;

        int right = nums.length-1;

        while(left<right){

            int mid = left+(right-left)/2;

            if(nums[mid]==target) return true;

            if(nums[mid]<nums[right]){

                if(target>nums[mid]&&target<nums[right]){

                    left = mid+1;

                }else if(target==nums[right]) return true;

                else{

                    right = mid-1;

                }

            }else if(nums[mid]>nums[right]){

                if(target>nums[left]&&target<nums[mid]){

                    right = mid-1;

                }else if(target==nums[left]) return true;

                else{

                    left = mid+1;

                }

            }else{

                right--;

            }

        }

        return nums[left]==target?true:false;

    }

}

这道题开始我想用先找最小元素然后在找制定元素来做,但是没有通过。原因是这时候realmid和realend是相等的,而此时的nums【realmid】是不等于target的,代码如下:

public class Solution {

    public boolean search(int[] nums, int target) {

        if(nums.length==0) return false;

        int left = 0;

        int right = nums.length-1;

        while(left<right){

            int mid = left+(right-left)/2;

            if(nums[mid]<nums[right]){

                right = mid;

            }else if(nums[mid]>nums[right]){

                left = mid+1;

            }else{

                right--;

            }

        }

        int min = left;

        left = 0;

        right = nums.length-1;

        while(left<=right){

            int mid = left+(right-left)/2;

            int realmid = (min+mid)%nums.length;

            if(nums[realmid]==target) return true;

            else if(nums[realmid]>target) right = mid-1;

            else left = mid+1;

        }

        return false;

    }

}

红线部分想改进但是不知道怎么改。

以上是关于81. Search in Rotated Sorted Array II的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 81. Search in Rotated Sorted Array II

81. Search in Rotated Sorted Array II

[Leetcode]81. Search in Rotated Sorted Array II

81. Search in Rotated Sorted Array II

81. Search in Rotated Sorted Array II

81. Search in Rotated Sorted Array II