博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Search for a Range
阅读量:2353 次
发布时间:2019-05-10

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

思路:

1、如果数组中不存在目标值 ,则返回[-1,-1]。

2、如果存在目标值,目标值索引为mid,上下范围为[i,j],然后进入处理子程序。

3、两个子处理程序,分别在[i,mid],[mid,j]中寻找目标值的边界。

题目:

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].

class Solution {public:    int fun1(vector
& nums, int low,int hi,int target) //寻找[i,mid]范围内的target边界 { int i=low; int j=hi; int mid; while(i<=j) { mid=(j-i)/2+i; if(nums[mid]
& nums, int low,int hi,int target) //寻找[mid,j]范围内的target边界 { int i=low; int j=hi; int mid; while(i<=j) { mid=(j-i)/2+i; if(nums[mid]>target) j=mid-1; else i=mid+1; } return j; } vector
searchRange(vector
& nums, int target) { vector
res(2,-1); int len=nums.size(); if(len==0) return res; int i=0; int j=len-1; int mid; while(i<=j) { mid=(j-i)/2+i; if(nums[mid]
target) j=mid-1; else { res[0]=fun1(nums,i,mid,target); res[1]=fun2(nums,mid,j,target); return res; } } return res; }};

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

你可能感兴趣的文章
将嵌套的数组扁平化
查看>>
vue-router的两种模式及区别
查看>>
c中嵌入python
查看>>
python的C扩展
查看>>
python的USB通信
查看>>
eclipse svn
查看>>
SPSS基础教程:SPSS统计分析基础
查看>>
IBM SPSS Modeler 客户端 vs 服务器的区别详解
查看>>
DataStage On Cloud,构建云端的企业数据集成平台
查看>>
ICMP协议
查看>>
SSL协议
查看>>
IMAP,POP3,SMTP协议
查看>>
数据库协议
查看>>
SNMP协议
查看>>
RDP远程桌面协议
查看>>
ssh Forward X11
查看>>
搜索引擎知识图谱相关结构化数据挖掘与去歧处理
查看>>
找到n个元素中的第二小元素
查看>>
linux命令之find
查看>>
linux命令学习之cut
查看>>