描述:
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.
思路:
本题木的特点是数组初始有序,然后循环移位了。
由于是循环移位,所以数组前一半或后一半至少有一半元素是有序的,而找到其中一半有序的元素正式本题的题眼。
1.初始start=0,end=len-1
2.mid=(start+end)/2;如果arr[mid]==target,找到元素
3.如果arr[start]<arr[mid],则前半部分有序,如果arr[start]<=target<arr[mid],则target存在的话肯定在前半部分,end=mid-1,如果target>arr[mid],则target存在的话肯定在后半部分,start=mid+1;
4.如果arr[start]>arr[mid],则后半部分有序,若果。。。。推理过程同3
5.如果arr[start]==arr[mid],start=start+1
代码:
public boolean search(int[] A, int target) { boolean hasNum=false; if(A==null||A.length==0) return hasNum; int start=0,end=A.length-1,mid=0; while(start<=end) { mid=(start+end)/2; if(A[mid]==target) { hasNum=true; break; }else { if(A[start]<A[mid]) { if(A[mid]>target&&A[start]<=target) end=mid-1; else start=mid+1; }else if(A[start]>A[mid]) { if(target>A[mid]&&target<=A[end]) start=mid+1; else end=mid-1; }else start++; } } return hasNum; }
leetcode_Search in Rotated Sorted Array II
原文地址:http://blog.csdn.net/mnmlist/article/details/45766015