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

分析:题意为在一个有序数组中找到给定目标值的起始位置并返回,如果目标值不存在则返回[1,1].

思路:使用binarySearchLow()去找到不小于目标值数字的最小索引,使用binarySearchUp()去找到不大于目标值数字的最大索引,然后即可得到索引范围。

code如下:

class Solution {
private:
int binarySearchLow(vector<int>& nums, int target, int begin, int end)
{
if(begin > end) return begin;
int mid = begin + (end - begin) / 2;
if(nums[mid] < target) return binarySearchLow(nums, target, mid + 1, end);
else return binarySearchLow(nums, target, begin, mid - 1);
}
int binarySearchUp(vector<int>& nums, int target, int begin, int end)
{
if(begin > end) return end;
int mid = begin + (end - begin) / 2;
if(nums[mid] > target) return binarySearchUp(nums, target, begin, mid - 1);
else return binarySearchUp(nums, target, mid + 1, end);
}
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> res(2, -1);
if(nums.empty()) return res;
int high = binarySearchUp(nums, target, 0, nums.size() -1);
int low = binarySearchLow(nums, target, 0, nums.size() - 1);
if(high >= low)
{
res[0] = low;
res[1] = high;
return res;
}
return res;
}
};

其他方法:先找到有序数组中与目标值相同的数字的位置,然后检查其个数.

code:

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int low=0;
int high=nums.size()-1;
vector<int> ans(2,-1);
int flag=-1; //数组中是否存在与目标值相同数字的标志
int start,end;
while(low<=high){
int mid=(low+high)/2;
if(nums[mid]<target){
low=mid+1;
}
else if(nums[mid]>target){
high=mid-1;
}
else{
flag=mid;
break;
}
}
if(flag!=-1){
start=flag;
while(start>=0 && nums[start]==target){
start--;
}
ans[0]=start+1;
end=flag;
while(end < nums.size() && nums[end]==target){
end++;
}
ans[1]=end-1;
}
return ans;
}
};

其他解法:解决问题的短代码(使用迭代器)

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ret;
vector<int>::iterator start = find(nums.begin(), nums.end(), target);
vector<int>::reverse_iterator end = find(nums.rbegin(), nums.rend(), target);
ret.push_back( (start == nums.end() ? -1 : start-nums.begin() ) ),ret.push_back(nums.size() - 1 - (end - nums.rbegin()));
return ret;
}
};

  

 

python:

class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if target not in nums:
return ([-1,-1])
low = nums.index(target)
nums.sort(reverse=True)
high = len(nums)-nums.index(target)-1
result = []
result.append(low)
result.append(high)
return (result)

  

 

  

leetcode:Search for a Range(数组,二分查找)的更多相关文章

  1. [LeetCode] #167# Two Sum II : 数组/二分查找/双指针

    一. 题目 1. Two Sum II Given an array of integers that is already sorted in ascending order, find two n ...

  2. LeetCode Search a 2D Matrix(二分查找)

    题意: 有一个矩阵,每行都有序,每行接在上一行尾后仍然有序.在此矩阵中查找是否存在某个数target. 思路: 这相当于用一个指针连续扫二维数组一样,一直p++就能到最后一个元素了.由于用vector ...

  3. [LeetCode] 74 Search a 2D Matrix(二分查找)

    二分查找 1.二分查找的时间复杂度分析: 二分查找每次排除掉一半不合适的值,所以对于n个元素的情况来说: 一次二分剩下:n/2 两次:n/4 m次:n/(2^m) 最坏情况是排除到最后一个值之后得到结 ...

  4. LeetCode OJ:Search for a Range(区间查找)

    Given a sorted array of integers, find the starting and ending position of a given target value. You ...

  5. [LeetCode] Search for a Range 搜索一个范围

    Given a sorted array of integers, find the starting and ending position of a given target value. You ...

  6. 【leetcode边做边学】二分查找应用

    很多其它请关注我的HEXO博客:http://jasonding1354.github.io/ 简书主页:http://www.jianshu.com/users/2bd9b48f6ea8/lates ...

  7. LeetCode: Search for a Range 解题报告

    Search for a RangeGiven a sorted array of integers, find the starting and ending position of a given ...

  8. Leetcode题目34.在排序数组中查找元素的第一个和最后一个位置(中等)

    题目描述: 给定一个按照升序排列的整数数组 nums,和一个目标值 target.找出给定目标值在数组中的开始位置和结束位置. 你的算法时间复杂度必须是 O(log n) 级别. 如果数组中不存在目标 ...

  9. PAT-1057 Stack (树状数组 + 二分查找)

    1057. Stack Stack is one of the most fundamental data structures, which is based on the principle of ...

  10. [LeetCode] Search for a Range [34]

    题目 Given a sorted array of integers, find the starting and ending position of a given target value. ...

随机推荐

  1. #!--->hashbang技术

    url中的#! URL 中的 # 本来的用途是跳转到页内锚点.一个 URL 中 # 后的值 (hash tag) 不影响所访问网页的内容,所以搜索引擎在处理仅仅 hash tag 不同的多个 URL ...

  2. vi编辑

    保存命令 按ESC键 跳到命令模式,然后: :w 保存文件但不退出vi :w file 将修改另外保存到file中,不退出vi :w! 强制保存,不推出vi :wq 保存文件并退出vi :wq! 强制 ...

  3. MariaDB集群Galera Cluster的研究与测试

    MariaDB集群Galera Cluster的研究与测试 Galera Cluster是MariaDB的一个双活多主集群,其可以使得MariDB的所有节点保持同步,Galera为MariaDB提供了 ...

  4. VMware workstation 的虚拟机中再安装workstation

    在VMware workstation 10中运行的虚拟机中再安装workstation软件时,启动时会出现不断重启的故障, 解决办法: 在宿主虚拟机的.vmx文件中添加一行 monitor_cont ...

  5. SPOJ375 Query on a tree(LCT边权)

    之前做了两道点权的LCT,这次做一下边权的LCT.上网找了一下资料,发现对于边权的LCT有这么两种处理方法,一种是每条边建一个点,于是边权就转成点权了.另外一种则是每个边权对应到点权上,也就是每个点对 ...

  6. 《Thinking in C++》学习笔记(一)【第二章】

    第二章 对象的创建与使用 2.1语言的翻译过程 翻译器分为两类:解释器(interpreter)和编译器(compiler). 2.1.1解释器 解释器将源代码转化成一些动作(它可由许多机器指令组成) ...

  7. ASP 中调用函数关于Call使用注意的问题

    Function TestFun(Tstr) TStr = "Fun2" End Function Sub TestSub(TStr) Tstr = "Sub2" ...

  8. GridControl的列显示成图片+文字,并且不同的文字对应不同的图片

    public static void SetDispatchStatus(GridView aGridView1, GridColumn aColStatus, bool aOnlyImage) { ...

  9. BZOJ 1877: [SDOI2009]晨跑 费用流

    1877: [SDOI2009]晨跑 Description Elaxia最近迷恋上了空手道,他为自己设定了一套健身计划,比如俯卧撑.仰卧起坐等 等,不过到目前为止,他坚持下来的只有晨跑. 现在给出一 ...

  10. 如何修改Linux系统的TTL值

    在网络中,黑客如果用ping命令去探测  一个主机,根据TTL基数可以推测操作系统的类型.对于一个没有经过任何网关和路由的网络, 直接ping对方系统得到的TTL值,被叫做"TTL基数&qu ...