-
Notifications
You must be signed in to change notification settings - Fork 1
/
firstAndLastOcc.java
97 lines (86 loc) · 2.43 KB
/
firstAndLastOcc.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import java.util.*;
public class firstAndLastocc {
public static int solve(int n, int x, int a[]) {
int first = -1;
for (int i = 0; i < a.length; i++) {
if (a[i] == x) {
first = i;
break;
}
}
return first;
}
public static int solve1(int a[], int n, int x) {
int last = -1;
for (int i = 0; i < a.length; i++) {
if (a[i] == x) {
last = x;
break;
}
}
return last;
}
public static int solve2(int a[], int x, int n) {
int start = 0;
int end = a.length - 1;
int first = -1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (a[mid] == x) {
first = a[mid];
start = mid + 1;
} else if (x < a[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return first;
}
public static int firstOccurrence(int a[], int n, int k) {
int low = 0, high = n - 1;
int first = -1;
while (low <= high) {
int mid = (low + high) / 2;
if (a[mid] == k) {
first = mid;
high = mid - 1;
} else if (a[mid] < k) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return first;
}
public static int lastOccurrence(int a[], int n, int k) {
int low = 0, high = n - 1;
int last = -1;
while (low <= high) {
int mid = (low + high) / 2;
if (a[mid] == k) {
last = mid;
low = mid + 1;
} else if (a[mid] < k) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return last;
}
public static int[] firstAndLastPosition(int a[], int n, int k) {
int first = firstOccurrence(a, n, k);
if (first == -1)
return new int[] { -1, -1 };
int last = lastOccurrence(a, n, k);
return new int[] { first, last };
}
public static void main(String[] args) {
int[] arr = { 2, 4, 6, 8, 8, 8, 11, 13 };
int n = arr.length;
int k = 8;
int[] ans = firstAndLastPosition(arr, n, k);
System.out.println(ans[0] + " " + ans[1]);
}
}