Skip to content

Commit 556f5a2

Browse files
committed
Added : Search in a Rotated Sorted Array
1 parent 1c6f5c8 commit 556f5a2

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
2+
3+
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
4+
5+
You are given a target value to search. If found in the array return its index, otherwise return -1.
6+
7+
You may assume no duplicate exists in the array.
8+
9+
Your algorithm's runtime complexity must be in the order of O(log n).
10+
11+
Example 1:
12+
13+
Input: nums = [4,5,6,7,0,1,2], target = 0
14+
Output: 4
15+
Example 2:
16+
17+
Input: nums = [4,5,6,7,0,1,2], target = 3
18+
Output: -1
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
@lc id : 33
3+
@problem : Search in Rotated Sorted Array
4+
@author : rohit
5+
@url : https://leetcode.com/problems/search-in-rotated-sorted-array/
6+
@difficulty : medium
7+
*/
8+
9+
class Solution {
10+
11+
public int binarySearch(int[] nums, int start, int end, int target){
12+
//Base Case
13+
if(start > end)
14+
return -1;
15+
16+
//Rec case
17+
int mid = (end + start) / 2;
18+
19+
if(nums[mid] == target)
20+
return mid;
21+
22+
//Checking where mid point lies
23+
//On first part or second part
24+
25+
//Mid lies in Left part or first line
26+
if(nums[start] <= nums[mid]){
27+
28+
if(target >= nums[start] && target <= nums[mid])
29+
return binarySearch(nums, start, mid-1, target);
30+
else return binarySearch(nums, mid+1, end, target);
31+
32+
}
33+
34+
//Mid lies in second line
35+
36+
if(target >= nums[mid] && target <= nums[end])
37+
return binarySearch(nums, mid+1, end, target);
38+
39+
return binarySearch(nums, start, mid-1, target);
40+
41+
}
42+
43+
public int search(int[] nums, int target) {
44+
return binarySearch(nums, 0, nums.length-1, target);
45+
46+
}
47+
}

0 commit comments

Comments
 (0)