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
- 34. Search for a Range
- 34. Search for a Range
- 34. Search for a Range
- 34. Search for a Range
- 34. Search for a Range
- 34. Search for a Range
- 34. Search for a Range
- 34. Search for a Range
- 34. Search for a Range
- 34. Search for a Range
- 34. Search for a Range
- 34. Search for a Range
- 34. Search for a Range
- 34. Search for a Range
- 34. Search for a Range
- 34. Search for a Range
- 34. Search for a Range
- 34. Search for a Range
- linux下sctp socket发送延迟问题
- python进阶15:继承、多态和多重继承
- 如何使用HTML5新增标签(一)
- Ant将Jmeter的jtl文件转为html文件报“前言中不允许有内容”
- 用cocos2dx打包时出现“make.exe: *** No rule to make target ”的解决方法
- 34. Search for a Range
- 生产者与消费者 Java代码描述
- SSD编译的时候出现问题
- Ubuntu16.04下使用sublime text3搭建Python IDE
- js笔记
- 【matlab】《图论》-完全图仿真
- 在项目中的总结
- 在pycharm中如何将django中多个app放到同个文件夹apps处理
- 往夜 -- 原来世界如此性感