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
| #if defined(MY_TEST)
#include <stdio.h> #include <string.h> #include <stdlib.h>
static int* str_to_array(char* str, int* numsSize) { int* arr = malloc(4096 * sizeof(int)), n = 0; char buf[4096], * p; strcpy(buf, str); for (p = strtok(buf, ", []"); p != NULL; p = strtok(NULL, ", []")) arr[n++] = strtol(p, 0, 0); *numsSize = n; return arr; }
int* searchRange(int* nums, int numsSize, int target, int* returnSize);
static void test(char* str, int target) { int n, * arr = str_to_array(str, &n); int* res = searchRange(arr, n, target, &n); printf("[%d,%d]\n", res[0], res[1]); }
int main(void) { test("[5, 7, 7, 8, 8, 10]", 8); // �����[3, 4] test("[5, 7, 7, 8, 8, 10]", 6); // �����[-1, -1] test("[]", 0); // �����[-1, -1] return 0; }
#endif
int* searchRange(int* nums, int numsSize, int target, int* returnSize) { int left = 0, right = numsSize, mid; static int ans[2];
ans[0] = ans[1] = -1;
while (left < right) { mid = (left + right) / 2; if (nums[mid] >= target) right = mid; else left = mid + 1; } if (left == numsSize || nums[left] != target) return ans; ans[0] = left;
left = 0; right = numsSize; while (left < right) { mid = (left + right) / 2; if (nums[mid] <= target) left = mid + 1; else right = mid; } ans[1] = left; return ans; }
|