您的位置:首页 > 其它

[Leetcode 88] 33 Search in Rotated Sorted Array

2013-07-26 12:56 399 查看
Problem:

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.

Analysis:

The problem is that the monotic property is broken after shiftting the array. Example is as follows:

Original Array: 1 2 3 4 5 6 7 8 9 10

Shifted Array1: 7 8 9 10 1 2 3 4 5 6

Shifted Array2: 5 6 7 8 9 10 1 2 3 4

For shifted array 1, the mid is 1 and for shifted array 2, the mid is 9. If now we search 10 in the two arrays, Which side should we go ? Both of 1 and 9 are less than 10, so it seems we need to go the left part of the array. But this is not ture for array2. And we also can decied which part to go with the addition information of A[0] and A[e].

One way I can think of is if we encount a sorted part of the array, then we use binary search. But if the part of the array is shifted, then we can only search both sides of the array.

Code:

Naive version:

class Solution {
public:
int search(int A[], int n, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int s = 0, e = n-1;

while (s <= e) {
int m = (s + e) / 2;

if (A[m] == target)
return m;
else if (A[m] < target) {
if (A[m] <= A[e]) {
if (A[e] < target)
e = m-1;
else
s = m+1;
} else {
s = m+1;
}
} else { // A[m] > target
if (A[m] >= A[s]) {
if (A[s] > target)
s = m + 1;
else
e = m - 1;
} else {
e = m-1;
}

}

}

return -1;
}
};


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: