leetcode_c++:Search for a Range(034)

题目

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


算法_1

  1. stl-使用lower_bound和upper_bound

算法_2

  1. 直接二分查找修改

复杂度

O(lgn)


#include
#include
#include 

using namespace std;

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int>::iterator lower=lower_bound(nums.begin(), nums.end(), target);
        //lower_bound返回第一个大于等于value值得位置
        vector<int>::iterator upper=upper_bound(nums.begin(), nums.end(), target);
        //upper 是第一个大于value值得位置


        vector<int> resultNo;
        resultNo.push_back(-1);
        resultNo.push_back(-1);

        vector<int> ret;
        ret.push_back(lower-nums.begin());
        ret.push_back(upper-nums.begin()-1);

        if(*lower !=target){

            return resultNo;

        }else{
            return ret;

        }


    }
};

#include
#include
#include 

using namespace std;

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target){
        vector<int> ret;
        ret.push_back(-1);
        ret.push_back(-1);

        int left=0,right=nums.size()-1,mid;
        while(left<=right){
            if(nums[left]==target && nums[right]==target){
                ret[0]=left;
                ret[1]=right;
                break;
            }

            mid=left+(right-left)/2;
            if(nums[mid]1;
            }else if(nums[mid]>target){
                right=mid-1;
            }else{
                if(nums[right]==target)
                    ++left;
                else
                    --right;
            }
        }

    return ret;

    }


};

你可能感兴趣的:(leetcode(c++))