Skip to content

Commit 02b48b4

Browse files
committed
search in rotated array
1 parent 8e270dd commit 02b48b4

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

Searching/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
|---|------------|------------|
2828
|1| [Find First and Last Position of Element in Sorted Array](https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/)|[Solution](find_first_and_last_position_of_element_in_sorted_array.cpp)|
2929
|2| [Single Element in a Sorted Array](https://leetcode.com/problems/single-element-in-a-sorted-array/)|[Solution](single_element_in_sorted_array.cpp)|
30-
|3| [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/)|Pending|
30+
|3| [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/)|[Solution](search_in_rotated_array.cpp)|
3131
|4| [Search in Rotated Sorted Array II](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/)|Pending|
3232
|5| [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/)|[Solution](min_in_rotated_arr.cpp)|
3333
|6| [Find Peak Element](https://leetcode.com/problems/find-peak-element/)|[Solution](peak_ele.cpp)|

Searching/search_in_rotated_array.cpp

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
int search(vector<int> &nums, int target)
5+
{
6+
int r = nums.size() - 1;
7+
int l = 0;
8+
while (l <= r)
9+
{
10+
int m = l + (r - l) / 2;
11+
if (nums[m] == target)
12+
return m;
13+
else if (nums[l] <= nums[m])
14+
{
15+
if (target >= nums[l] && target <= nums[m])
16+
{
17+
r = m - 1;
18+
}
19+
else
20+
l = m + 1;
21+
}
22+
else
23+
{
24+
if (target >= nums[m] && target <= nums[r])
25+
{
26+
l = m + 1;
27+
}
28+
else
29+
r = m - 1;
30+
}
31+
}
32+
return -1;
33+
}
34+
35+
int main()
36+
{
37+
int n, tar;
38+
cin >> n >> tar;
39+
vector<int> v;
40+
for (int i = 0; i < n; i++)
41+
{
42+
int temp;
43+
cin >> temp;
44+
v.push_back(temp);
45+
}
46+
cout << search(v, tar) << endl;
47+
return 0;
48+
}

0 commit comments

Comments
 (0)