leetcode-Search for a Range

来源:互联网 发布:mac被灭雷欧为什么不救 编辑:程序博客网 时间:2024/06/06 07:08
Difficulty: Medium

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(logn).

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

class Solution {    int my_lowerBound(vector<int> &nums,int target){        int left =0;                int right=nums.size()-1;                while(left<=right){            int mid=left+(right-left)/2;                        if(nums[mid]==target){                if(mid==0||nums[mid-1]!=target)                    return mid;                else                    right=mid-1;            }            else if(nums[mid]>target)                right=mid-1;            else                left=mid+1;        }        return -1;    }    int my_upperBound(vector<int> &nums,int target){        int left =0;        int size=nums.size();        int right=size-1;         while(left<=right){            int mid=left+(right-left)/2;                        if(nums[mid]==target){                if(mid==size-1||nums[mid+1]!=target)                    return mid;                else                    left=mid+1;            }            else if(nums[mid]>target)                right=mid-1;            else                left=mid+1;        }        return -1;    }public:    vector<int> searchRange(vector<int>& nums, int target) {             return {my_lowerBound(nums,target),my_upperBound(nums,target)};    }};


0 0