1+ package leetcode .editor .en ;
2+ 3+ class FindFirstAndLastPositionOfElementInSortedArray {
4+ 5+ //leetcode submit region begin(Prohibit modification and deletion)
6+ class Solution {
7+ public int [] searchRange (int [] nums , int target ) {
8+ int start = universalBinarySearch (0 , nums .length , (i ) -> {
9+ if (nums [i ] == target && (i == 0 || nums [i - 1 ] < target )) return 0 ;
10+ if (nums [i ] < target ) return 1 ;
11+ else return -1 ;
12+ });
13+ int end = universalBinarySearch (0 , nums .length , (i ) -> {
14+ if (nums [i ] == target && (i + 1 == nums .length || nums [i + 1 ] > target )) return 0 ;
15+ if (nums [i ] > target ) return -1 ;
16+ else return 1 ;
17+ });
18+ return new int []{start , end };
19+ }
20+ 21+ 22+ /**
23+ * Returns the value {@code low <= i < high} for which {@code cmp(i) == 0}, assuming that
24+ * for all {@code j > i}, {@code cmp(j) < 0} and for all {@code j < i}, {@code cmp(j) > 0}.
25+ * @param low lower bound of i (inclusive)
26+ * @param high upper bound of i (exclusive)
27+ * @param cmp function of an integer that returns a valid integer as described above for all
28+ * {@code low <= i < high}
29+ * @return appropriate value of {@code i} such that {@code cmp(i) == 0}. If there are more than one such values,
30+ * may return any of them.
31+ */
32+ int universalBinarySearch (int low , int high , IntComparator cmp ){
33+ while (low < high ){
34+ int midpoint = low + high >> 1 ;
35+ int result = cmp .compare (midpoint );
36+ if (result == 0 ) return midpoint ;
37+ if (result < 0 ){
38+ high = midpoint ;
39+ } else {
40+ low = midpoint + 1 ;
41+ }
42+ }
43+ return -1 ;
44+ }
45+ 46+ @ FunctionalInterface
47+ interface IntComparator {
48+ /**
49+ * Determines if the desired value is the given one (zero), a smaller one (negative value) or a greater
50+ * one (positive value).
51+ */
52+ int compare (int index );
53+ }
54+ }
55+ //leetcode submit region end(Prohibit modification and deletion)
56+ 57+ 58+ }
0 commit comments