Skip to content

Commit a598c77

Browse files
committed
feat : search-in-rotated-sorted-array
1 parent 0bb77e5 commit a598c77

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
3+
input : rotated array
4+
output : index of target else -1
5+
6+
4 5 6 7 0 1 2
7+
target = 6
8+
return 2
9+
10+
solution1) brute force
11+
return index after loop
12+
tc : O(n)
13+
sc : O(1)
14+
15+
solution2)
16+
separte array into 2 parts to make sure each part is sorted.
17+
find the rotated point, binary search for target
18+
O(logn) + O(logn)
19+
20+
tc : O(logn)
21+
sc : O(1)
22+
*/
23+
class Solution {
24+
public int search(int[] nums, int target) {
25+
int l = 0;
26+
int r = nums.length - 1;
27+
while(l < r) {
28+
int mid = (r - l) / 2 +l;
29+
if(nums[mid] <= nums[r]) {
30+
r = mid;
31+
} else {
32+
l = mid + 1;
33+
}
34+
}
35+
// determine which part
36+
int start = 0;
37+
int end = nums.length - 1;
38+
if(nums[start] <= target && nums[Math.max(0, l-1)] >= target) {
39+
end = Math.max(0, l - 1);
40+
} else if (nums[l] <= target && nums[end] >= target){
41+
start = l;
42+
}
43+
44+
while(start <= end) {
45+
int mid = (end - start) / 2 + start;
46+
if(nums[mid] == target) {
47+
return mid;
48+
} else if (nums[mid] < target) {
49+
start = mid + 1;
50+
} else {
51+
end = mid - 1;
52+
}
53+
}
54+
return -1;
55+
}
56+
}

0 commit comments

Comments
 (0)