Skip to content

Commit ac048b8

Browse files
committed
search ortated arr
1 parent cc528db commit ac048b8

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

DSA Crack Sheet/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@
9595

9696
- [First and last occurrences of X](https://practice.geeksforgeeks.org/problems/first-and-last-occurrences-of-x/0# "view question") - [Cpp Solution](./solutions/First%20and%20last%20occurrences%20of%20X.cpp)
9797
- [Value equal to index value](https://practice.geeksforgeeks.org/problems/value-equal-to-index-value1330/1# "view question") - [Cpp Solution](./solutions/Value%20equal%20to%20index%20value.cpp)
98+
- [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/ "view question") - [Cpp Solution](./solutions/Search%20in%20Rotated%20Sorted%20Array.cpp)
9899
- []( "view question") - [Cpp Solution](./solutions/.cpp)
99100

100101
### Linked-List
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*
2+
Search in Rotated Sorted Array
3+
==============================
4+
5+
There is an integer array nums sorted in ascending order (with distinct values).
6+
7+
Prior to being passed to your function, nums is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].
8+
9+
Given the array nums after the rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.
10+
11+
Example 1:
12+
Input: nums = [4,5,6,7,0,1,2], target = 0
13+
Output: 4
14+
15+
Example 2:
16+
Input: nums = [4,5,6,7,0,1,2], target = 3
17+
Output: -1
18+
19+
Example 3:
20+
Input: nums = [1], target = 0
21+
Output: -1
22+
23+
Constraints:
24+
1 <= nums.length <= 5000
25+
-104 <= nums[i] <= 104
26+
All values of nums are unique.
27+
nums is guaranteed to be rotated at some pivot.
28+
-104 <= target <= 104
29+
30+
Follow up: Can you achieve this in O(log n) time complexity?
31+
*/
32+
33+
class Solution
34+
{
35+
public:
36+
int search(vector<int> &nums, int target)
37+
{
38+
int i = 0, j = nums.size() - 1, mid = -1;
39+
while (i <= j)
40+
{
41+
mid = (i + j) / 2;
42+
43+
if (target == nums[mid])
44+
return mid;
45+
if (nums[i] <= nums[mid])
46+
{
47+
if (target <= nums[mid] && target >= nums[i])
48+
j = mid - 1;
49+
else
50+
i = mid + 1;
51+
}
52+
else
53+
{
54+
if (target >= nums[mid] && target <= nums[j])
55+
i = mid + 1;
56+
else
57+
j = mid - 1;
58+
}
59+
}
60+
return -1;
61+
}
62+
};

0 commit comments

Comments
 (0)