-
Notifications
You must be signed in to change notification settings - Fork 30
/
SearchforaRange.cs
executable file
·92 lines (87 loc) · 5.06 KB
/
SearchforaRange.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Source : https://leetcode.com/problems/search-for-a-range/
// Author : codeyu
// Date : Monday, October 17, 2016 7:37:08 PM
/**********************************************************************************
*
* Given a sorted array of integers, find the starting and ending position of a given target value.
*
* Your algorithm's runtime complexity must be in the order of O(log n).
*
* If the target is not found in the array, return [-1, -1].
*
*
* For example,
* Given [5, 7, 7, 8, 8, 10] and target value 8,
* return [3, 4].
*
*
**********************************************************************************/
using System;
using System.Collections.Generic;
using Algorithms.Utils;
namespace Algorithms
{
public class Solution034
{
public static int[] SearchRange(int[] nums, int target)
{
var start = -1;
var end = -1;
if(nums != null && nums.Length > 0)
{
int left = 0, right = nums.Length - 1;
while(left < right-1)
{
var mid = left + (right - left) / 2;
if(nums[mid] == target)
{
right = mid;
}
else if(nums[mid] < target)
{
left = mid;
}
else
{
right = mid;
}
}
if(nums[left] ==target)
{
start = left;
}
else if(nums[right] == target)
{
start = right;
}
left = 0;
right = nums.Length - 1;
while(left < right-1)
{
var mid = left + (right - left) / 2;
if(nums[mid] == target)
{
left = mid;
}
else if(nums[mid] < target)
{
left = mid;
}
else
{
right = mid;
}
}
if(nums[right] == target)
{
end = right;
}
else if(nums[left] == target)
{
end = left;
}
}
return new []{start, end};
}
}
}