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. 2014ACM/ICPC亚洲区北京站 上交命题

    A http://acm.hdu.edu.cn/showproblem.php?pid=5112 输入n个时刻和位置,问那两个时刻间速度最快. 解法:按照时间排序,然后依次求相邻两个之间的速度,速度= ...

  2. iNode for linux install

    http://wenku.baidu.com/link?url=953T6GZCnaBzwr4YqPFUT4oOyYr4wyOnXlCLO1OUYZkaJWh2fTs634SM7ZpYiTKkpmYX ...

  3. html5离线存储

    为了提升Web应用的用户体验,我们在做网站或者webapp的时候,经常需要保存一些内容到本地.例如,用户登录token,或者一些不经常变动的数据. 随着HTML5的到来,出现了诸如AppCache.l ...

  4. windows_phone指定时间后执行函数

    开发windows phone 应用程序时需要在一段指定的时间后执行某些函数,于是乎想到了通过DispatcherTimer类来实现,再在.Tick后面添加自己想要的事件 DispatcherTime ...

  5. JAVA数据结构系列 栈

    java数据结构系列之栈 手写栈 1.利用链表做出栈,因为栈的特殊,插入删除操作都是在栈顶进行,链表不用担心栈的长度,所以链表再合适不过了,非常好用,不过它在插入和删除元素的时候,速度比数组栈慢,因为 ...

  6. JavaScript之四种继承方式讲解

    在Javascript中,所有开发者定义的类都可以作为基类,但出于安全性考虑,本地类和宿主类不能作为基类,这样可以防止公用访问编译过的浏览器级的代码,因为这些代码可以被用于恶意攻击. 选定基类后,就可 ...

  7. 简单CSS hack:区分IE6、IE7、IE8、Firefox、Opera

    一.跨浏览器的网页设计一直是让人很头疼的问题,这不只是因为浏览器的版本众多,还有一个重要的原因是相同浏览器的不同时期的版本也会有差异,甚至是在不同操作同台上还会有不同.因此使CSS hack技术进行浏 ...

  8. HDU4871 Shortest-path tree(树分治)

    好久没做过树分治的题了,对上一次做是在南京赛里跪了一道很裸的树分治题后学的一道,多校的时候没有看这道题,哪怕看了感觉也看不出来是树分治,看出题人给了解题报告里写了树分治就做一下好了. 题意其实就是给你 ...

  9. KMP模板,最小循环节

    (可以转载,但请注明出处!) 下面是有关学习KMP的参考网站 http://blog.csdn.net/yaochunnian/article/details/7059486 http://blog. ...

  10. POJ 1491

    #include<iostream> #include<cmath> #include<iomanip> #define MAXN 50 using namespa ...