-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfirstandlastoccurence.java
67 lines (58 loc) · 1.92 KB
/
firstandlastoccurence.java
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public class firstandlastoccurence {
public static void main(String[] args) {
int[] nums = { 5, 7, 7, 8, 8, 10 };
firstlast(nums, 5);
}
public static int[] firstlast(int[] nums, int target) {
int low = 0;
int high = nums.length - 1;
int[] ans = { -1, -1 }; // Default value if target is not found
// Find the first occurrence (lower bound)
while (low <= high) {
int mid = low + (high - low) / 2;
if (nums[mid] == target) {
ans[0] = mid; // Store the index
high = mid - 1; // Continue searching in the left half
} else if (nums[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
// Reset low and high for finding the last occurrence (upper bound)
low = 0;
high = nums.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (nums[mid] == target) {
ans[1] = mid; // Store the index
low = mid + 1; // Continue searching in the right half
} else if (nums[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
System.out.println(ans[0] + " " + ans[1]); // Print the correct indices
return ans;
}
public static int[] bound(int[] nums, int target) {
int start = -1;
int end = -1;
int[] ans = new int[2];
for (int i = 0; i < nums.length; i++) {
if (start == -1) {
if (nums[i] == target) {
start = i;
}
}
if (start != -1 && nums[i] == target) {
end = i;
}
}
ans[0] = start;
ans[1] = end;
System.out.println(ans[0] + " - " + ans[1]);
return ans;
}
}