Skip to content

Commit 02c89e3

Browse files
Sean PrashadSean Prashad
authored andcommitted
Update 33_Search_in_Rotated_Sorted_Array.java
1 parent 67a49c6 commit 02c89e3

File tree

1 file changed

+18
-31
lines changed

1 file changed

+18
-31
lines changed

Modified Binary Search/33_Search_in_Rotated_Sorted_Array.java

Lines changed: 18 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -4,42 +4,29 @@ public int search(int[] nums, int target) {
44
return -1;
55
}
66

7-
int left = 0, right = nums.length - 1;
7+
int result = -1, low = 0, high = nums.length - 1;
88

9-
while (left < right) {
10-
int mid = left + ((right - left) / 2);
11-
12-
if (nums[mid] > nums[right]) {
13-
left = mid + 1;
14-
} else {
15-
right = mid;
16-
}
17-
}
18-
19-
int start = left;
20-
left = 0;
21-
right = nums.length - 1;
22-
23-
if (target >= nums[start] && target <= nums[right]) {
24-
left = start;
25-
} else {
26-
right = start;
27-
}
28-
29-
while (left <= right) {
30-
int mid = left + ((right - left) / 2);
9+
while (low <= high) {
10+
int mid = low + (high - low) / 2;
3111

3212
if (nums[mid] == target) {
33-
return mid;
34-
}
35-
36-
if (nums[mid] < target) {
37-
left = mid + 1;
13+
result = mid;
14+
break;
15+
} else if (nums[mid] >= nums[low]) {
16+
if (target >= nums[low] && target < nums[mid]) {
17+
high = mid;
18+
} else {
19+
low = mid + 1;
20+
}
3821
} else {
39-
right = mid - 1;
22+
if (target >= nums[mid] && target <= nums[high]) {
23+
low = mid + 1;
24+
} else {
25+
high = mid;
26+
}
4027
}
4128
}
4229

43-
return -1;
30+
return result;
4431
}
45-
}
32+
}

0 commit comments

Comments
 (0)