34. Search for a Range

来源:互联网 发布:华为交换机端口ip 编辑:程序博客网 时间:2024/06/06 04:51

Given an array of integers sorted in ascending order, 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].

/** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */int comp(void const*a, void const*b){return *(int*)a - *(int*)b;}int* searchRange(int* nums, int numsSize, int target, int* returnSize) {    int* result;int leftBound, rightBound;int* ptr;int index, i, aleftBound, arightBound, mid;*returnSize = 2;result = (int*) calloc(*returnSize, sizeof(int));ptr = (int*) bsearch(&target, nums, numsSize, sizeof(int), comp);if(ptr == NULL) // not found{result[0] = result[1] = -1;}else {index = ptr - nums;//寻找左边界 aleftBound = 0;arightBound = index;while(aleftBound <= arightBound - 2){mid = (arightBound + aleftBound) >> 1;if(nums[mid] == target)arightBound = mid;else aleftBound = mid;}if(nums[aleftBound] == target)leftBound = aleftBound;else leftBound = arightBound;//寻找右边界aleftBound = index;arightBound = numsSize - 1;while(aleftBound <= arightBound - 2){mid = (arightBound + aleftBound) >> 1;if(nums[mid] == target)aleftBound = mid;else arightBound = mid;}if(nums[arightBound] == target)rightBound = arightBound;else rightBound = aleftBound;result[0] = leftBound;result[1] = rightBound;}return result;}

在上述代码中,第一次寻找存不存在,可以不使用bsearch, 直接用自己的二分查找法, 去判断mid的值和target的值的大小关系来确定左右边界的变化,这样做可以方便如果存在的这种情况,缩小寻找的 左右边界的范围

0 0