Skip to content

Commit 1b246be

Browse files
committed
Add 081_Search_in_Rotated_Sorted_Array.cpp
1 parent 26f6a7d commit 1b246be

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
// Problem 81, Search in Rotated Sorted Array II
2+
3+
// Follow up for "Search in Rotated Sorted Array":
4+
// What if duplicates are allowed?
5+
// Would this affect the run-time complexity? How and why?
6+
// Write a function to determine if a given target is in the array.
7+
//
8+
// FYI: "Search in Rotated Sorted Array":
9+
// Suppose a sorted array is rotated at some pivot unknown to you beforehand.
10+
// (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
11+
// You are given a target value to search. If found in the array return its index, otherwise return -1.
12+
// You may assume no duplicate exists in the array.
13+
14+
#include <stddef.h>
15+
#include <vector>
16+
#include <string.h>
17+
#include <stdio.h>
18+
#include <algorithm>
19+
#include <iostream>
20+
#include <map>
21+
22+
using namespace std;
23+
24+
class Solution {
25+
public:
26+
bool search(vector<int>& nums, int target) {
27+
28+
int start = 0;
29+
int end = nums.size()-1;
30+
31+
while(start <= end){
32+
// skip the repeating numbers on both sides
33+
while(start < end && nums[start] == nums[start + 1]) start++;
34+
while(start < end && nums[end] == nums[end - 1]) end--;
35+
36+
int mid = (start + end)/2;
37+
if(nums[mid] == target) return true; // found
38+
if(nums[mid] < target){
39+
// for cases like {6 7 0 1 2 4 5} mid is 1, start is 6, end is 5, target is 2
40+
// and cases like {2 4 5 6 7 0 1} mid is 6, start is 2, end is 1, target is 7
41+
if(nums[start] > target || nums[mid] >= nums[start])
42+
start = mid + 1;
43+
else
44+
end = mid - 1;
45+
}
46+
else{
47+
// for cases like {4 5 6 7 0 1 2}, mid is 7, start is 4, end is 2, target is 5
48+
// and cases like {6 7 0 1 2 4 5}, mid is 1, start is 6, end is 5, target is 0
49+
if(nums[start] <= target || nums[mid] < nums[start])
50+
end = mid - 1;
51+
else
52+
start = mid + 1;
53+
}
54+
}
55+
return false;
56+
}
57+
};
58+
int main()
59+
{
60+
Solution* sol = new Solution();
61+
vector<int> nums;
62+
nums.push_back(4);
63+
nums.push_back(5);
64+
nums.push_back(6);
65+
nums.push_back(7);
66+
nums.push_back(0);
67+
nums.push_back(1);
68+
nums.push_back(2);
69+
70+
cout<<sol->search(nums,3)<<endl;
71+
cout<<sol->search(nums,0)<<endl;
72+
cout<<sol->search(nums,6)<<endl;
73+
cout<<sol->search(nums,5)<<endl;
74+
75+
char c;
76+
cin>>c;
77+
78+
return 0;
79+
}

0 commit comments

Comments
 (0)