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

problem Given an array of integers sorted in ascending order, find the starting and ending posi...

LeetCode OJ-34.Search for a Range

LeetCode OJ-34.Search for a Range题目描述 Given an array of integers sorted in ascending order, find t...

leetcode 34. Search for a Range

import java.util.Stack; //Given a sorted array of integers, find the starting and ending position o...

leetcode 34. Search for a Range-数组边界|二分查找

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

LeetCode Algorithms 34. Search for a Range

题目难度: Medium 原题描述: Given an array of integers sorted in ascending order, find the starting...

Search for a Range - LeetCode 34

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

LeetCode OJ-34-Search for a Range

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

34. Search for a Range

二分查找

LeetCode - 34. Search for a Range

这道题目可以使用两次二分搜索来解决,第一次找到target的左range,第二次找到targe的右range。 在第一次二分搜索中,我们分别将两个指针i和j设置为0和n - 1,根据nums[mid...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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