http://oj.leetcode.com/problems/search-in-rotated-sorted-array-ii/
class Solution {
public:
// The time complexity is O(N) in worest case
// For example, A[]={1,1,1,1,1,1,1,1,1,1} and target=2
bool search(int A[], int n, int target) {
int left=0, right=n-1;
while(left<=right){
int mid=(left+right)/2;
if(A[mid]==target||A[left]==target) return true;
if(A[left]<A[mid]){
if(target>A[left]&&target<A[mid]) right=mid-1;
else left=mid+1;
}
else if(A[left]>A[mid]){
if(target>A[left]||target<A[mid]) right=mid-1;
else left=mid+1;
}
else left++;
}
return false;
}
};
本文介绍了一个针对旋转有序数组进行目标值查找的算法实现。通过分析数组特性,采用分治法思想,利用中间值与目标值的关系来缩小搜索范围,最终找到目标值。此算法在最坏情况下的时间复杂度为O(N)。
364

被折叠的 条评论
为什么被折叠?



