34. Search for a Range

原创 2016年08月30日 20:30:46

二分搜索,在找最左端,要找的目标值小于target,所以最后必定left指向最左端,right指向最左端的前一个数字,同理,最右端

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int n=nums.size();
        int left=0,right=n-1,mid;
        int L,R;
        vector<int> ans{-1,-1};
        bool find=false;
        while(left<=right)
        {
            mid=(left+right)>>1;
            if(nums[mid]==target)
            {
                find=true;
                break;
            }
            else if(nums[mid]>target)
                right=mid-1;
            else
                left=mid+1;
        }
        if(!find)
            return ans;
        
        left=0,right=mid;
        while(left<=right)
        {
            mid=(left+right)>>1;
            if(nums[mid]==target)
                right=mid-1;
            else if(nums[mid]<target)
                left=mid+1;
        }
        L=left;
        left=mid,right=n-1;
        while(left<=right)
        {
            mid=(left+right)>>1;
            if(nums[mid]==target)
                left=mid+1;
            else if(nums[mid]>target)
                right=mid-1;
        }
        R=right;
        ans[0]=L;
        ans[1]=R;
        return ans;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

【LeetCode】34. Search for a Range

题目描述Given an array of integers sorted in ascending order, find the starting and ending position of a...

34. Search for a Range

34. Search for a Range Given an array of integers sorted in ascending order, find the starting a...

leetcode34_Search for a Range

一.问题描述 Given a sorted array of integers, find the starting and ending position of a given targe...

LeetCode 34 Search For A Range 二叉查找相关(二)

题目: https://leetcode.com/problems/search-for-a-range/ Given a sorted array of integers, find the s...

leetcode:34. Search for a Range

Given an array of integers sorted in ascending order, find the starting and ending position of a giv...

leetcode 34. Search for a Range

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

LeetCode34——Search for a Range

LeetCode34——Search for a Range 题意: 在有序序列中找到重复出现的数字出现的范围,返回一个二元组代表范围的闭区间,如果找不到target则返回[-1,-1] ...

【LeetCode】34. Search for a Range

【LeetCode】34. Search for a Range

【LeetCode-34】Search for a Range

这道题属于二分查找的运用,leetcode很多都是把二分查找稍微改变一下就行,不多说了,上代码了 public class SearchforaRange { int[] result = n...

[LeetCode34]Search for a Range

Given a sorted array of integers, find the starting and ending position of a given target value. Yo...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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