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

这破题,把我弄的心烦意乱,就是三次折半,不过后两次有些特殊 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
  • 970

[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...

LeetCode_34---Search for a Range

Given a sorted array of integers, find the starting and ending position of a given target value. Yo...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:34. Search for a Range
举报原因:
原因补充:

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