您的位置:首页 > 职场人生

[LeetCode] Search In Rotated Sorted Array

2014-01-01 04:49 281 查看
问题:

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.
分析:
首先遍历一次肯定是可以找到,但这明显不是最佳答案。其次,如果我们知道在什么位置rotate的,那我们也可以找到,但我们不用这么麻烦其实。如果我们用binary search,观察可发现,每次找到中点之后,总有半边是已经sorted过的。这让我们有了使用binary search的可能。我们只需要判断target是不是在sorted那半边:如果是,则在那半边找;如果不是,则在另外一个半边找。因为用来判断的那半边是sorted,所以判断这个操作可以在O(1)时间完成。

代码:(O(log n))

class Solution {
public:
int search(int A[], int n, int target) {
int start = 0;
int end = n - 1;
while (start <= end) {
int half = start + (end - start) / 2;

if (A[half] == target) return half;

// the left half is sorted
if (A[start] <= A[half]) {
if (A[start] <= target && A[half] > target)
end = half - 1;
else
start = half + 1;
}

// the right half is sorted
else {
if (A[half] < target && A[end] >= target)
start = half + 1;
else
end = half - 1;
}
}
return -1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法 面试