Skip to content

Commit 85fa21a

Browse files
Create FirstAndLastPosition.java
1 parent c411051 commit 85fa21a

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

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

0 commit comments

Comments
 (0)