forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
searchInRotatedSortedArray.II.cpp
68 lines (57 loc) · 1.92 KB
/
searchInRotatedSortedArray.II.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Source : https://oj.leetcode.com/problems/search-in-rotated-sorted-array-ii/
// Author : Hao Chen
// Date : 2014-06-29
/**********************************************************************************
*
* 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.
*
**********************************************************************************/
class Solution {
public:
bool search(int A[], int n, int key) {
if (n<=0) return false;
if (n==1){
return (A[0]==key) ? true : false;
}
int low=0, high=n-1;
while( low<=high ){
if (A[low] < A[high] && ( key < A[low] || key > A[high]) ) {
return false;
}
//if dupilicates, them binary search the duplication
while (low < high && A[low]==A[high]){
low++;
}
int mid = low + (high-low)/2;
if ( A[mid] == key ) return true;
//the target in non-rotated array
if (A[low] < A[mid] && key >= A[low] && key< A[mid]){
high = mid - 1;
continue;
}
//the target in non-rotated array
if (A[mid] < A[high] && key > A[mid] && key <= A[high] ){
low = mid + 1;
continue;
}
//the target in rotated array
if (A[low] > A[mid] ){
high = mid - 1;
continue;
}
//the target in rotated array
if (A[mid] > A[high] ){
low = mid + 1;
continue;
}
//reach here means nothing found.
low++;
}
return false;
}
};