博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Search for a Range--查找某个数范围--二分查找
阅读量:4108 次
发布时间:2019-05-25

本文共 1594 字,大约阅读时间需要 5 分钟。

问题:

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] and target value 8,
return [3, 4].

解答:

先二分查找,再前后搜索。

注意边界条件,如果搜索到头尾该怎么办。

代码:

class Solution {public:    vector
searchRange(int A[], int n, int target) { int result,i; vector
re_list; result = b_search(A, n, target); if(result == -1) { re_list.push_back(result); re_list.push_back(result); } else { i = result; while(i >= 0) { if((i-1)<0 ||(A[i-1] != A[i])) { re_list.push_back(i); break; } else --i; } i = result; while(i <= n-1) { if((i+1)>=n || A[i+1] != A[i]) { re_list.push_back(i); break; } else ++i; } } return re_list; } int b_search(int A[], int n, int target) { int start,end,mid; start = 0; end = n-1; while(start <= end) { mid = start+(end-start)/2; if(A[mid] == target) { return mid; } if(A[mid] < target) { start = mid+1; } else { end = mid-1; } } return -1; }};

转载地址:http://oktsi.baihongyu.com/

你可能感兴趣的文章
Vue动态生成el-checkbox点击无法选中的解决方法
查看>>
python __future__
查看>>
MySQL Tricks1
查看>>
python 变量作用域问题(经典坑)
查看>>
pytorch
查看>>
pytorch(二)
查看>>
pytorch(三)
查看>>
pytorch(四)
查看>>
pytorch(5)
查看>>
pytorch(6)
查看>>
opencv 指定版本下载
查看>>
ubuntu相关
查看>>
C++ 调用json
查看>>
nano中设置脚本开机自启动
查看>>
动态库调动态库
查看>>
Kubernetes集群搭建之CNI-Flanneld部署篇
查看>>
k8s web终端连接工具
查看>>
手绘VS码绘(一):静态图绘制(码绘使用P5.js)
查看>>
手绘VS码绘(二):动态图绘制(码绘使用Processing)
查看>>
基于P5.js的“绘画系统”
查看>>