1+ /*
2+ * Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
3+
4+ * Your algorithm's runtime complexity must be in the order of O(log n).
5+
6+ * If the target is not found in the array, return [-1, -1].
7+
8+ * For example,
9+ * Given [5, 7, 7, 8, 8, 10] and target value 8,
10+ * return [3, 4].
11+ * Created by supercoderx on 2017/8/12.
12+ */
13+ #include <stdio.h>
14+ #include <stdlib.h>
15+
16+ int * searchRange (int * nums , int numsSize , int target , int * returnSize ) {
17+ * returnSize = 2 ;
18+ int * result = malloc (sizeof (int ) * 2 );
19+ result [0 ] = -1 ;
20+ result [1 ] = -1 ;
21+ if (numsSize == 0 ) {
22+ return result ;
23+ }
24+
25+ int left = 0 , right = numsSize - 1 , mid , start , end ;
26+ while (left <= right ) {
27+ mid = (left + right ) / 2 ;
28+ if (nums [mid ] == target ) {
29+ start = end = mid ;
30+ while (start >= 0 ) {
31+ if (nums [start ] != nums [mid ]) {
32+ start ++ ;
33+ break ;
34+ }
35+ if (start == 0 ) {
36+ break ;
37+ }
38+ start -- ;
39+ }
40+ while (end <= numsSize - 1 ) {
41+ if (nums [end ] != nums [mid ]) {
42+ end -- ;
43+ break ;
44+ }
45+ if (end == numsSize - 1 ) {
46+ break ;
47+ }
48+ end ++ ;
49+ }
50+ result [0 ] = start ;
51+ result [1 ] = end ;
52+ return result ;
53+ } else if (nums [mid ] < target ) {
54+ left = mid + 1 ;
55+ } else {
56+ right = mid - 1 ;
57+ }
58+ }
59+ return result ;
60+ }
61+
62+ void testSearchRange () {
63+ int a [] = {5 , 7 , 7 , 7 , 7 , 8 , 8 , 10 }, b [] = {1 }, count = 0 ;
64+ int * res = searchRange (b , 1 , 1 , & count );
65+
66+ printf ("[%d,%d]" , res [0 ], res [1 ]);
67+
68+ }
0 commit comments