Skip to content

Commit b046c8c

Browse files
committed
Add Solution.java to problems 0034
1 parent e4f5e91 commit b046c8c

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

Diff for: solution/0034.Find First and Last Position of Element in Sorted Array/Solution.java

+2
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ public int[] searchRange(int[] nums, int target) {
1111
}
1212
return new int[]{-1,-1};
1313
}
14+
1415
private int findFirst(int[] nums, int start, int end, int target) {
1516
while (start < end) {
1617
int temp = start + (end - start) / 2;
@@ -19,6 +20,7 @@ private int findFirst(int[] nums, int start, int end, int target) {
1920
}
2021
return start;
2122
}
23+
2224
private int findEnd(int[] nums, int start, int end, int target) {
2325
while (start < end) {
2426
int temp = start + (end - start + 1) / 2;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution {
2+
public int[] searchRange(int[] nums, int target) {
3+
int left = 0, right = nums.length - 1;
4+
while (left <= right) {
5+
int mid = left + (right - left) / 2;
6+
if (nums[mid] == target) {
7+
int resL = mid, resR = mid;
8+
while (resL > left && nums[resL - 1] == target) resL--;
9+
while (resR < right && nums[resR + 1] == target) resR++;
10+
return new int[]{resL, resR};
11+
}
12+
if (nums[mid] > target) {
13+
right = mid - 1;
14+
} else {
15+
left = mid + 1;
16+
}
17+
}
18+
return new int[]{-1, -1};
19+
}
20+
}

0 commit comments

Comments
 (0)