判斷旋轉數組中是否含有某個值 Search in Rotated Sorted Array II

問題:this

Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?spa

Would this affect the run-time complexity? How and why?code

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.get

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).it

Write a function to determine if a given target is in the array.io

The array may contain duplicates.function

解決:class

① 本題容許有重複的值,這樣Search in Rotated Sorted Array中的條件就不能判斷哪一邊爲有序序列了。因此要將mid移動一下。好比:{1,3,1,1,1,1}im

若是nums[start] <= nums[mid] 條件就不能肯定[start mid]區間爲遞增有序序列,咱們就把該條件分紅兩個字條件:sort

nums[start] < nums[mid] 則 [start mid]區間爲遞增有序序列

nums[start] = nums[mid] 則[start mid]區間不能肯定,那就start ++,往下一步看看便可。

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

相關文章
相關標籤/搜索