【LeetCode & 剑指offer刷题】查找与排序题8:Search for a Range

【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

Search for a Range

Given an array of integers nums 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].
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

C+
 
/*问题:在有序数组中查找目标值出现的范围
方法:对于有序序列用二分查找
使用stl中lower_bound和upper_bound函数
O(logn)
*/
class Solution
{
public:
    vector<int> searchRange(vector<int>& nums, int target)
    {
        if(nums.empty()) return vector<int>{-1,-1}; //容器为空时 vector<int>{}为初始化返回容器操作)
     
        //lower_bound找到后返回第一个大于等于target的位置的迭代器,否则返回迭代器end
        vector<int>::iterator start = lower_bound(nums.begin(), nums.end(),target);
        //upper_bound找到后返回第一个大于target的位置的迭代器,否则返回迭代器end
        vector<int>::iterator end = upper_bound(nums.begin(), nums.end(), target);
       
        if(start == end || start == nums.end())//相等时,说明找到的是大于目标值的数,指向end时说明目标值比数组所有元素大,两种情况下均为没有找到
            return {-1,-1};
        else
            return {start-nums.begin(), end-nums.begin()-1};
    }
};
 
/*
//或者自己实现
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
    vector<int> result;
    int begin = 0;
    int end = nums.size() - 1;
    int start_index = -1;
    int end_index = -1;
    //locate the start_index
    while (begin <= end){
        int mid = (begin + end) / 2;
        if (nums[mid] == target){
            if (mid - 1<0 || nums[mid - 1] != target){
                start_index = mid;
                break;
            }
            else{
                end = mid - 1;
            }
        }
        else if (nums[mid]>target){
            end = mid - 1;
        }
        else{
            begin = mid + 1;
        }
    }
    //locate the end_index
    begin = 0;
    end = nums.size() - 1;
    while (begin <= end){
        int mid = (begin + end) / 2;
        if (nums[mid] == target){
            if (mid + 1>nums.size() - 1 || nums[mid + 1] != target){
                end_index = mid;
                break;
            }
            else{
                begin = mid + 1;
            }
        }
        else if (nums[mid]>target){
            end = mid - 1;
        }
        else{
            begin = mid + 1;
        }
    }
    //cout << start_index << " " << end_index << endl;
    result.push_back(start_index);
    result.push_back(end_index);
    return result;
}
};
*/
 

 

posted @ 2019-01-05 20:12  wikiwen  阅读(153)  评论(0编辑  收藏  举报