Skip to content

Commit 45b83f8

Browse files
committed
fd
1 parent 5ffe352 commit 45b83f8

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

solution/src/main/java/com/inuker/solution/SearchForARange.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,41 @@
66

77
public class SearchForARange {
88

9+
/**
10+
* TestCase
11+
* [1], 0
12+
* [1], 1
13+
*/
914
public int[] searchRange(int[] nums, int target) {
15+
if (nums.length == 0) {
16+
return new int[]{-1, -1};
17+
}
18+
int first = firstHigherEqual(nums, target);
19+
if (first == nums.length || nums[first] != target) {
20+
return new int[] {
21+
-1, -1
22+
};
23+
}
24+
return new int[] {
25+
first,
26+
firstHigherEqual(nums, target + 1) - 1
27+
};
28+
}
29+
30+
private int firstHigherEqual(int[] nums, int target) {
31+
int left = 0, right = nums.length;
32+
while (left < right) {
33+
int mid = (left + right) / 2;
34+
if (nums[mid] < target) {
35+
left = mid + 1;
36+
} else {
37+
right = mid;
38+
}
39+
}
40+
return left;
41+
}
42+
43+
public int[] searchRange2(int[] nums, int target) {
1044
if (nums.length == 0) {
1145
return new int[]{-1, -1};
1246
}

test/src/main/java/com/inuker/test/main.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package com.inuker.test;
22

3+
import com.inuker.solution.SearchForARange;
34
import com.leetcode.library.ListNode;
45
import com.leetcode.library.RandomListNode;
56
import com.leetcode.library.TreeNode;
@@ -27,5 +28,11 @@
2728
public class main {
2829

2930
public static void main(String[] args) {
31+
int[] range = new SearchForARange().searchRange(new int[] {
32+
1, 2, 3, 3, 4
33+
}, 3);
34+
for (int n : range) {
35+
System.out.print(n + " ");
36+
}
3037
}
3138
}

0 commit comments

Comments
 (0)