Search in Rotated Sorted Array ||
Suppose a sorted array 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
).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
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.
ref:http://fisherlei.blogspot.com/2013/01/leetcode-search-in-rotated-sorted-array_3.html
[解题思路]
确实有影响。比如,上一题(http://fisherlei.blogspot.com/2013/01/leetcode-search-in-rotated-sorted-array.html)的程序中默认如果A[m]>=A[l],那么[l,m]为递增序列的假设就不能成立了,比如如下数据
[1,3,1,1,1]
所以,要是想增强该假设,有两个选择
1. 对于每一个递增序列,遍历之,确认。
2. 找到pivot点,然后确定对应序列搜索。
Update: 3/18/2013. add the implementation
重新想了一下,其实不需要这么复杂。如果A[m]>=A[l]不能确定递增,那就把它拆分成两个条件
1. A[m]>A[l] 递增
2. A[m] ==A[l] 确定不了,那就l++,往下看一步即可。
public class Solution { public boolean search(int[] A, int target) { int len = A.length; int l = 0; int r = len -1; while(l <= r){ int m = (l+r)/2; if(target == A[m]){ return true; } if( A[m] < A[l]){ // higher is sorted if(target > A[m] && target <= A[r]){ l = m+1; }else{ r = m-1; } }else if(A[m] > A[l]){ if(target >= A[l] && target < A[m]){ r = m-1; }else{ l = m+1; } }else{ // A[m] == A[l] l++; } } return false; } }