Skip to content

Commit 40a9f6c

Browse files
author
Li Li
committed
add code of 34
1 parent bc66e66 commit 40a9f6c

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// direct thought
2+
public class Solution {
3+
public int[] SearchRange(int[] nums, int target) {
4+
int[] res = new int[2] { -1, -1 };
5+
if (nums == null || nums.Length == 0) return res;
6+
int start = FindLeftIndex(nums, target);
7+
// if starting point not found, then return not found res[]
8+
if (start == -1) return res;
9+
int end = FindRightIndex(nums, target); // no need to check not found again.
10+
res[0] = start;
11+
res[1] = end;
12+
return res;
13+
}
14+
private int FindLeftIndex(int[] nums, int target) {
15+
int left = 0, right = nums.Length - 1;
16+
while (left + 1 < right) {
17+
int mid = left + (right - left) / 2;
18+
if (nums[mid] < target) {
19+
left = mid;
20+
} else {
21+
right = mid;
22+
}
23+
}
24+
if (nums[left] == target) return left;
25+
if (nums[right] == target) return right;
26+
return -1;
27+
}
28+
private int FindRightIndex(int[] nums, int target) {
29+
int left = 0, right = nums.Length - 1;
30+
while (left + 1 < right) {
31+
int mid = left + (right - left) / 2;
32+
if (nums[mid] <= target) {
33+
left = mid;
34+
} else {
35+
right = mid;
36+
}
37+
}
38+
if (nums[right] == target) return right;
39+
if (nums[left] == target) return left;
40+
return -1;
41+
}
42+
}

0 commit comments

Comments
 (0)