Search for a Range
2015-07-20 12:45
330 查看
Given a sorted array of integers, 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] andtarget value 8,
return [3, 4].
思路:本题还是在考察二分查找法的使用。首先使用二分查找找到一个target的位置,该位置将数组分为两个子数组,左边的子数组都是小于等于target,右边的子数组都是大于等于target。可以再利用二分查找,分别找到target的边界。代码如下:
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] andtarget value 8,
return [3, 4].
思路:本题还是在考察二分查找法的使用。首先使用二分查找找到一个target的位置,该位置将数组分为两个子数组,左边的子数组都是小于等于target,右边的子数组都是大于等于target。可以再利用二分查找,分别找到target的边界。代码如下:
/** * Return an arrayof size *returnSize. * Note: Thereturned array must be malloced, assume caller calls free(). */ int* searchRange(int* nums, int numsSize, int target, int* returnSize) { int resleft, resright; int left, right; int mid = -1; int resmid; left = 0; right = numsSize - 1; while(left <= right) { mid = left + (right-left)/2; if(nums[mid] == target) { break; } if(nums[mid] > target) { right -= 1; } else { left += 1; } } if(left > right) { int *res = calloc(2, sizeof(int)); res[0] = -1; res[1] = -1; *returnSize = 2; return res; } left = 0; right = mid; while(left < right) { resmid = left + (right-left)/2; if(nums[resmid] < target) { left = resmid+1; } else { right = resmid; } } resleft = left; left = mid; right = numsSize - 1; while(left <= right) { resmid = left + (right-left)/2; if(nums[resmid] == target) { left = resmid+1; } else { right = resmid-1; } } resright = right; int *res = calloc(2, sizeof(int)); res[0] = resleft; res[1] = resright; *returnSize = 2; return res; }
相关文章推荐
- c++ .net winform 应用程序调用dll(gSOAP调用WebService)获取天气
- SPOJ 1825 Free tour II
- Java-发送邮件(附件、图片)---(五)实例
- 扩展MARA 添加Z字段BAPI_TE_MARA
- Nginx源代码分析之accept(十)
- REST无状态的理解
- Xcode6加载langchImage所需图片尺寸
- ios学习路线
- Navicat Premium11.0.16 for mac 破解
- ZOJ 3789 - Gears (并查集)
- MongoDB3.0发布--新特性
- sigaction信号处理
- JavaScript DOM操作表格及样式
- 18 4Sum
- Nginx源代码分析之网络超时管理(九)
- JDK环境变量配置以及可能出现的问题
- 弹球游戏
- 弹球游戏
- 弹球游戏
- 弹球游戏