forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0034-find-first-and-last-position-of-element-in-sorted-array.cs
51 lines (44 loc) · 1.38 KB
/
0034-find-first-and-last-position-of-element-in-sorted-array.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public class Solution {
public int[] SearchRange(int[] nums, int target)
{
int first = -1, last = -1;
first = searchEle(nums, target, true);
if (first == -1)
return new int[] { first, last };
last = searchEle(nums, target, false);
return new int[] { first, last };
}
public int searchEle(int[] nums, int target, bool isStart)
{
int n = nums.Length;
int start = 0, end = nums.Length - 1;
while (start <= end)
{
int mid = (start + end )/ 2;
if (nums[mid] == target)
{
if (isStart)
{
if (mid == start || nums[mid - 1] != target)
{
return mid;
}
end = mid - 1;
}
else
{
if (mid == end || nums[mid + 1] != target)
{
return mid;
}
start = mid + 1;
}
}
else if (nums[mid] > target)
end = mid - 1;
else
start = mid + 1;
}
return -1;
}
}