码迷,mamicode.com
首页 > 其他好文 > 详细

81. Search in Rotated Sorted Array II

时间:2017-02-01 10:48:31      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:class   nbsp   get   exit   minimum   neu   sea   false   ted   

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

标签:class   nbsp   get   exit   minimum   neu   sea   false   ted   

原文地址:http://www.cnblogs.com/codeskiller/p/6359784.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!