Skip to content

Commit 8d0a057

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 34_Find_First_and_Last_Position_of_Element_in_Sorted_Array.java
1 parent 4af02ef commit 8d0a057

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
class Solution {
2+
public int[] searchRange(int[] nums, int target) {
3+
if (nums == null || nums.length == 0) {
4+
return new int[] { -1, -1 };
5+
}
6+
7+
int[] result = new int[2];
8+
result[0] = binarySearchHelperLow(nums, target);
9+
result[1] = binarySearchHelperHigh(nums, target);
10+
11+
return result;
12+
}
13+
14+
private int binarySearchHelperLow(int[] nums, int target) {
15+
int low = 0, high = nums.length - 1;
16+
17+
int idx = -1;
18+
19+
while (low <= high) {
20+
int mid = low + (high - low) / 2;
21+
22+
if (nums[mid] == target) {
23+
idx = mid;
24+
}
25+
26+
if (nums[mid] >= target) {
27+
high = mid - 1;
28+
} else {
29+
low = mid + 1;
30+
}
31+
}
32+
33+
return idx;
34+
}
35+
36+
private int binarySearchHelperHigh(int[] nums, int target) {
37+
int low = 0, high = nums.length - 1;
38+
39+
int idx = -1;
40+
41+
while (low <= high) {
42+
int mid = low + (high - low) / 2;
43+
44+
if (nums[mid] == target) {
45+
idx = mid;
46+
}
47+
48+
if (nums[mid] <= target) {
49+
low = mid + 1;
50+
} else {
51+
high = mid - 1;
52+
}
53+
}
54+
55+
return idx;
56+
}
57+
}

0 commit comments

Comments
 (0)