[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.,
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;
}
};
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e.,
0 1 2 4 5 6 7might 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;
}
};
相关文章推荐
- Search in Rotated Sorted Array_Leetcode_#33
- 【92】【H】【leetcode】 Search in Rotated Sorted Array
- Leetcode 33 Search in Rotated Sorted Array
- LeetCode 33---Search in Rotated Sorted Array
- LeetCode 31.Next Permutation & 33.Search in Rotated Sorted Array
- [leetcode] Search in Rotated Sorted Array Python
- [Leetcode] Search in a Rotated Sorted Array
- [LeetCode]Search in Rotated Sorted Array
- [LeetCode 33]Search in Rotated Sorted Array (二分查找)
- [LeetCode]Search in Rotated Sorted Array II
- LeetCode(33)Search in Rotated Sorted Array
- [Leetcode]_33 Search in Rotated Sorted Array
- LeetCode--Search in Rotated Sorted Array
- LeetCode Search in Rotated Sorted Array
- leetcode-Search in Rotated Sorted Array
- Leetcode 33, 81 Search in Rotated Sorted Array I, II
- [leetcode] 81. Search in Rotated Sorted Array II
- 【Leetcode】Search in Rotated Sorted Array
- leetcode-33. Search in Rotated Sorted Array
- Leetcode Search in Rotated Sorted Array