先看解法:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static inline int* binarySeach(int* result, int* nums, int numsSize, int target) {
int mid = (int)(numsSize / 2);
int left_index = 0, right_index = numsSize - 1;
while (left_index <= mid) {
if (nums[left_index] == target) {
if (result[0] == -1)
result[0] = left_index;
result[1] = left_index;
}
left_index++;
}
while (right_index >= mid) {
if (nums[right_index] == target) {
if (result[0] == -1 || result[0] > right_index)
result[0] = right_index;
if (result[1] == -1 || result[1] < right_index)
result[1] = right_index;
}
right_index--;
}
return result;
}
static inline int* searchRange(int* nums, int numsSize, int target, int* returnSize) {
int *result = malloc(sizeof(int) * 2);
memset(result, -1, sizeof(int) * 2);
*returnSize = 2;
if (!nums)
return result;
if (!returnSize)
return result;
if (numsSize <= 0)
return result;
if (numsSize == 1){
if (nums[0] == target )
memset(result, 0x0, sizeof(int) * 2);
return result;
}
return binarySeach(result, nums, numsSize, target);
}
int main(int argc, char const *argv[])
{
int returnSize = 0; // 返回的结果集必须为2;
int nums_size = 6; // 数组大小必须与nums一致;
int target = 6; // 要查找的数字必须大于等于0;
int nums[] = {5,7,7,8,8,10}; // 数组
int *result = searchRange(nums, nums_size, target, &returnSize);
if (result == 2)
printf("left = [%d], right = [%d], returnSize = [%d]\n", result[0], result[1], returnSize);
return 0;
}
一拍脑子写的二分查找法, 提交后测试结果最快8ms,
优化空间主要在于将归并循环, 但是这样会降低可读性.
同时没有大心思钻进去玩, 发出来博大家一笑吧!