Skip to content

Commit 5353180

Browse files
authored
Create 0034_FindFIRST_and_last_pos.java
1 parent bb202c6 commit 5353180

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

0034_FindFIRST_and_last_pos.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution {
2+
public int[] searchRange(int[] nums, int target) {
3+
4+
5+
int[] ans = {-1, -1};
6+
// check for first occurrence if target first
7+
ans[0] = search(nums, target, true);
8+
if (ans[0] != -1) {
9+
ans[1] = search(nums, target, false);
10+
}
11+
return ans;
12+
}
13+
14+
// this function just returns the index value of target
15+
int search(int[] nums, int target, boolean findStartIndex) {
16+
int ans = -1;
17+
int start = 0;
18+
int end = nums.length - 1;
19+
while(start <= end) {
20+
// find the middle element
21+
// int mid = (start + end) / 2; // might be possible that (start + end) exceeds the range of int in java
22+
int mid = start + (end - start) / 2;
23+
24+
if (target < nums[mid]) {
25+
end = mid - 1;
26+
} else if (target > nums[mid]) {
27+
start = mid + 1;
28+
} else {
29+
// potential ans found
30+
ans = mid;
31+
if (findStartIndex) {
32+
end = mid - 1;
33+
} else {
34+
start = mid + 1;
35+
}
36+
}
37+
}
38+
return ans;
39+
}
40+
}
41+
42+

0 commit comments

Comments
 (0)