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. HDU 1532 Drainage Ditches 分类: Brush Mode 2014-07-31 10:38 82人阅读 评论(0) 收藏

    Drainage Ditches Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) ...

  2. TGL站长关于常见问题的回复

    问题地址: http://www.thegrouplet.com/thread-112923-1-1.html 问题: 网站配有太多的模板是否影响网站加载速度 月光答复: wp不需要删除其他的模板,不 ...

  3. frequentism-and-bayesianism-chs

    frequentism-and-bayesianism-chs 频率主义和贝叶斯主义——一个实用的介绍 此notebook最初出现在博客Pythonic Perambulations的文章.BSD l ...

  4. .NET设计模式(5):工厂方法模式(Factory Method)(转)

    工厂方法模式(Factory Method) ——.NET设计模式系列之五 Terrylee,2004年1月2日 概述 在软件系统中,经常面临着“某个对象”的创建工作,由于需求的变化,这个对象的具体实 ...

  5. HDOJ 1069 DP

    开启DP之路 题目:http://acm.hdu.edu.cn/showproblem.php?pid=1069 描述一下: 就是给定N(N<=20)个方体,让你放置,求放置的最高高度,限制条件 ...

  6. Sqli-labs less 58

    Less-58 执行sql语句后,并没有返回数据库当中的数据,所以我们这里不能使用union联合注入,这里使用报错注入. Payload:http://127.0.0.1/sqli-labs/Less ...

  7. Sql注入一种dump所有数据的方法

    Select exp(~(select*from(select(concat(@:=0,(select count(*)from`information_schema`.columns where t ...

  8. codeforces 442C C. Artem and Array(有深度的模拟)

    题目 感谢JLGG的指导! 思路: //把数据转换成一条折线,发现有凸有凹 //有凹点,去掉并加上两边的最小值//无凹点,直接加上前(n-2)个的和(升序)//数据太大,要64位//判断凹与否,若一边 ...

  9. idHTTP访问百度

    百度屏蔽了indy的客户端标识的 Mozilla/3.0 (compatible; Indy Library),把‘Indy Library’去掉就可以了. try IdHTTP1.Request.U ...

  10. 40页PPT告诉你真正的"互联网+"

    点这里 40页PPT告诉你真正的"互联网+" 2015-04-06 网站分析公会 超过50万名互联网从业人士关注 互联网运营领域最具影响力自媒体 本文根据和君赵大伟关于互联网思维大 ...