首页 > 学院 > 开发设计 > 正文

LeetCode 34. Search for a Range

2019-11-08 03:08:46
字体:
来源:转载
供稿:网友

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

Your algorithm's runtime complexity must be in the order of O(log n).

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

answer:

class Solution {public:    vector<int> searchRange(vector<int>& nums, int target) {        int head = -1,tail = -1,start = 0,end = nums.size() - 1;        mySearch(nums,start,end,target,head,tail);        vector<int> result;        result.push_back(head);        result.push_back(tail);        return result;    }        void mySearch(vector<int>& nums, int start, int end, int target, int & head,int & tail){        if(start > end) return;        int mid = (start + end) / 2;        if(nums[mid] < target){            mySearch(nums,mid + 1,end,target,head,tail);        }        else if(nums[mid] > target){            mySearch(nums,start,mid - 1,target,head,tail);        }        else{            int i = mid;            while(i < nums.size() && nums[i] == target) i++;            if( i > mid) tail = i - 1;            else tail = i;            i = mid;            while(i >= 0 && nums[i] == target) i--;            if(i < mid) head = i + 1;            else head = i;            return;        }    }};


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表