-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
searchInRotatedSortedArray.II.cpp
77 lines (67 loc) · 2.24 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
69
70
71
72
73
74
75
76
77
// 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.
*
**********************************************************************************/
// Using the same idea "Search in Rotated Sorted Array"
// but need be very careful about the following cases:
// [3,3,3,4,5,6,3,3]
// [3,3,3,3,1,3]
// After split, you don't know which part is rotated and which part is not.
// So, you have to skip the ducplication
// [3,3,3,4,5,6,3,3]
// ^ ^
// [3,3,3,3,1,3]
// ^ ^
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, remove 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;
}
};