forked from super30admin/Binary-Search-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirstAndLastPosofEleInArray.Java
More file actions
49 lines (38 loc) · 1.35 KB
/
FirstAndLastPosofEleInArray.Java
File metadata and controls
49 lines (38 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
Time complexity - O(Log N)
Space Complexity - O(1)
*/
class Solution {
public int[] searchRange(int[] nums, int target) {
int firstOccurrence = this.findBound(nums, target, true);
if (firstOccurrence == -1)
return new int[]{-1, -1};
int lastOccurrence = this.findBound(nums, target, false);
return new int[]{firstOccurrence, lastOccurrence};
}
private int findBound(int[] nums, int target, boolean isFirst) {
int N = nums.length;
int begin = 0, end = N - 1;
while (begin <= end) {
int mid = (begin + end) / 2;
if (nums[mid] == target) {
if (isFirst) {
if (mid == begin || nums[mid - 1] != target) {
return mid;
}
end = mid - 1;
} else {
if (mid == end || nums[mid + 1] != target) {
return mid;
}
begin = mid + 1;
}
} else if (nums[mid] > target) {
end = mid - 1;
} else {
begin = mid + 1;
}
}
return -1;
}
}