22
33public class _0034_FindFirstAndLastPositionOfElementInSortedArray_4 {
44 // tag::answer[]
5-
65 /**
76 * @author D瓜哥 · https://www.diguage.com
87 * @since 2025-11-27 22:43:47
98 */
109 public int [] searchRange (int [] nums , int target ) {
10+ int left = binarySearch (nums , target );
11+ if (left == nums .length || nums [left ] != target ) {
12+ return new int []{-1 , -1 };
13+ }
14+ int right = binarySearch (nums , target + 1 );
15+ return new int []{left , right - 1 };
16+ }
17+
18+ private int binarySearch (int [] nums , int target ) {
1119 int left = 0 , right = nums .length - 1 ;
1220 while (left <= right ) {
1321 int mid = left + (right - left ) / 2 ;
@@ -20,25 +28,7 @@ public int[] searchRange(int[] nums, int target) {
2028 right = mid - 1 ;
2129 }
2230 }
23- if (right < 0 || left == nums .length || nums [left ] != target ) {
24- return new int []{-1 , -1 };
25- }
26- int a = left ;
27-
28- left = 0 ;
29- right = nums .length - 1 ;
30- while (left <= right ) {
31- int mid = left + (right - left ) / 2 ;
32- // 循环不变量:
33- // nums[left-1] >= target
34- // nums[right+1] < target
35- if (target < nums [mid ]) {
36- right = mid - 1 ;
37- } else {
38- left = mid + 1 ;
39- }
40- }
41- return new int []{a , right };
31+ return left ;
4232 }
4333 // end::answer[]
4434}
0 commit comments