File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
Algorithms Basics/Chapter 6. Binary Search Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments