Skip to content

Commit c094bed

Browse files
committed
优化34
1 parent f965961 commit c094bed

File tree

1 file changed

+10
-20
lines changed

1 file changed

+10
-20
lines changed

src/main/java/com/diguage/algo/leetcode/_0034_FindFirstAndLastPositionOfElementInSortedArray_4.java

Lines changed: 10 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,20 @@
22

33
public 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

Comments
 (0)