Search in Rotated Sorted Array II:带重复与转折的升序数列搜索

来源:互联网 发布:python 并行编程 编辑:程序博客网 时间:2024/06/08 00:23

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.

思路:判断是否严格升序数列+重复时缩小边界,可以参考前三篇博客。

class Solution {    public boolean search(int[] nums, int target) {         if(nums.length==0) return false;        int s = 0;        int e = nums.length-1;        while(s<=e){            int m = (s+e)/2;            if(nums[m]==target){                return true;            }            if(nums[s]<=nums[m]){//严格s-m段严格升序数列                if(nums[s]==nums[m]&&s!=m){//判断是否有重复                    s++;                }else{                    if(nums[s]<=target&&target<nums[m]){//target落在严格升序区间                        e = m-1;                    }else{                        s = m+1;                    }                }            }else{                if(nums[m]==nums[e]&&e!=m){                    e--;                }else{                    if(nums[m]<target&&target<=nums[e]){                        s = m+1;                    }else{                        e = m-1;                    }                }            }                   }        return false;    }}



阅读全文
0 0
原创粉丝点击