Middle-题目65:34. Search for a Range

原创 2016年05月31日 16:35:16

题目原文:
Given a sorted array of integers, find the starting and ending position of a given target value.
题目大意:
给出排序好的数组,寻找目标值所在的下标区间。如果目标值不存在,返回[-1,-1].
题目分析:
朴素解法是逐一比较,找到开始节点后再向后找,优化解法是使用两次二分查找。而二分查找可以使用C++的lower_bound和upper_bound两个内置的接口实现。(这个学习了。)
源码:(language:cpp)

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        auto p1 = lower_bound(nums.begin(), nums.end(), target);

        auto p2 = upper_bound(nums.begin(), nums.end(), target);

        vector<int> res; res.clear();
        if(*p1 != target) {
            res.push_back(-1);
            res.push_back(-1);
            return res;
        }

        res.push_back(p1 - nums.begin());
        res.push_back(p2 - nums.begin() - 1);

        return res;
    }
};

成绩:
12ms,beats 7.83%,众数12ms, 90.36%

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

[C++]LeetCode: 65 Search for a Range

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

leetcode-34 Search for a Range

这破题,把我弄的心烦意乱,就是三次折半,不过后两次有些特殊 class Solution { public: vector searchRange(int A[], int n, int t...
  • sole_cc
  • sole_cc
  • 2015年04月14日 15:22
  • 321

Leetcode-34. Search for a Range

Given a sorted array of integers, find the starting and ending position of a given target value. Yo...
  • mcf171
  • mcf171
  • 2016年10月03日 20:11
  • 142

[LeetCode] Search for a Range [34]

题目 Given a sorted array of integers, find the starting and ending position of a given target value. ...
  • swagle
  • swagle
  • 2014年06月13日 11:14
  • 966

[leetcode]34. Search for a Range(Java实现)

leetcode测试地址:https://leetcode.com/problems/search-for-a-range/#/description Given an array ...

[LeetCode]34.Search for a Range

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

Leetcode NO.34 Search for a Range

题目要求如下: Given a sorted array of integers, find the starting and ending position of a given targ...

<LeetCode OJ> 34. Search for a Range

34. Search for a Range My Submissions Question Total Accepted: 75021 Total Submissions: 261472 D...

[LeetCode-Java]34. Search for a Range

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

【LeetCode OJ 34】Search for a Range

题目链接:https://leetcode.com/problems/search-for-a-range/ 题目:Given a sorted array of integers, find th...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Middle-题目65:34. Search for a Range
举报原因:
原因补充:

(最多只允许输入30个字)