Skip to content

Commit dd34462

Browse files
authored
Update Find First and Last Position of Element in Sorted Array.java
1 parent de95ca1 commit dd34462

File tree

1 file changed

+31
-23
lines changed

1 file changed

+31
-23
lines changed
Lines changed: 31 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,35 @@
11
class Solution {
2-
public int[] searchRange(int[] nums, int target) {
3-
return new int[]{binarySearchHelper(nums, target, -1), binarySearchHelper(nums, target, 1)};
4-
}
5-
6-
private int binarySearchHelper(int[] nums, int target, int direction) {
7-
int idx = -1;
8-
int start = 0;
9-
int end = nums.length - 1;
10-
while (start <= end) {
11-
int mid = (start + end) / 2;
12-
if (nums[mid] == target) {
13-
idx = idx == -1 ? mid : (direction == -1 ? Math.min(mid, idx) : Math.max(mid, idx));
14-
if (direction == -1) {
15-
end = mid - 1;
16-
} else {
17-
start = mid + 1;
2+
3+
private static enum Position {
4+
FIRST, LAST;
5+
}
6+
7+
public int[] searchRange(int[] nums, int target) {
8+
return new int[]{
9+
search(nums, target, Position.FIRST),
10+
search(nums, target, Position.LAST)
11+
};
12+
}
13+
14+
private static int search(int[] nums, int target, Position position) {
15+
int left = 0;
16+
int right = nums.length - 1;
17+
int idx = -1;
18+
while (left <= right) {
19+
int mid = (left + right) / 2;
20+
if (nums[mid] == target) {
21+
idx = mid;
22+
if (position == Position.FIRST) {
23+
right = mid - 1;
24+
} else {
25+
left = mid + 1;
26+
}
27+
} else if (nums[mid] > target) {
28+
right = mid - 1;
29+
} else {
30+
left = mid + 1;
31+
}
1832
}
19-
} else if (nums[mid] > target) {
20-
end = mid - 1;
21-
} else {
22-
start = mid + 1;
23-
}
33+
return idx;
2434
}
25-
return idx;
26-
}
2735
}

0 commit comments

Comments
 (0)