-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch_in_rotated_sorted_array2.cpp
More file actions
83 lines (79 loc) · 2.03 KB
/
search_in_rotated_sorted_array2.cpp
File metadata and controls
83 lines (79 loc) · 2.03 KB
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
78
79
80
81
82
83
/*
* =====================================================================================
*
* Filename: search_in_rotated_sorted_array2.cpp
*
* Description: Search in Rotated Sorted Array II.
*
* Version: 1.0
* Created: 03/22/19 09:23:48
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <vector>
class Solution
{
public:
bool search(const std::vector<int>& nums, int target)
{
int start = 0;
int end = nums.size() - 1;
while (start <= end)
{
int pivot = (start + end) / 2;
if (nums[pivot] == target)
{
// Found target
return true;
}
if (nums[pivot] == nums[end])
{
end--;
}
else if (nums[pivot] == nums[start])
{
start++;
}
else if (nums[pivot] < nums[end])
{
// Right half is ascending
if (nums[pivot] > target || nums[end] < target)
{
end = pivot - 1;
}
else
{
start = pivot + 1;
}
}
else
{
// Left half is ascending
// nums[pivot] > nums[end]
if (nums[start] > target || nums[pivot] < target)
{
start = pivot + 1;
}
else
{
end = pivot - 1;
}
}
}
return false;
}
};
int main(int argc, char* argv[])
{
std::vector<int> nums = {2, 2, 2, 2, 3, 2, 2, 2};
auto found = Solution().search(nums, 3);
printf("Found index? %s\n", (found ? "Yes" : "No"));
return 0;
}