您的位置:首页 > 其它

leetcode -- Search in Rotated Sorted Array II

2013-08-01 20:38 316 查看
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.

上题中A[l] <= A[m]在数组中有重复元素时无法保证[l,m]是sorted

当输入:[1,3,1,1,1], 3

这里参考:

分为两种情形:http://fisherlei.blogspot.com/2013/01/leetcode-search-in-rotated-sorted-array_3.html

1. A[l] < A[m] 则[l, m]是递增的

2. A[l] = A[m] 此时是重复元素,无法确认哪一部分是有序的,则跳过l,l++

public class Solution {
public boolean search(int[] A, int target) {
// Start typing your Java solution below
// DO NOT write main() function
int len = A.length;

// binary search
int l = 0;
int r = len - 1;
while(l <= r){
int m = (l + r) / 2;
if(target == A[m])
return true;

// lower is sorted
if(A[l] < A[m]){
if(A[l] <= target && target < A[m])
r = m - 1;
else{
l = m + 1;
}
} else if(A[l] > A[m]) {
// upper is sorted
if(A[m] < target && target <= A[r]){
l = m + 1;
} else{
r = m - 1;
}
} else {
l = l + 1;
}
}
return false;
}
}


ref:

二分搜索及其扩展

http://www.pcw8510.com/?p=3294
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: