Search in Rotated Sorted Array II

来源:互联网 发布:php找工作去哪里好 编辑:程序博客网 时间:2024/06/09 04:13

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.

public class Solution {    public boolean search(int[] A, int target) {        if(A==null || A.length<=0) return false;        int index1=0;        int index2=A.length;        int midIndex=index1;        //if(A.length==1 && A[0]==target) return true;        while(index1!=index2){            midIndex=index1+(index2-index1)/2;            if(A[midIndex]==target) return true;            else if(A[index1]<A[midIndex]){                if(A[index1]<=target && target<A[midIndex]){                    index2=midIndex;                }                else{                    index1=midIndex+1;                }            }            else if(A[index1]>A[midIndex]){                if(A[midIndex]<=target && target<=A[index2-1]){                    index1=midIndex+1;                }                else{                    index2=midIndex;                }            }            else{                //skip duplicate elements                index1++;            }        }        return false;    }}

0 0
原创粉丝点击