LeetCode 34. Search for a Range

Description

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

my program

(1)时间复杂度为O(n)

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int i = 0, j = nums.size() -1;
        vector<int> res;
        while (i < nums.size())
        {
            if (nums[i] == target)  
                break;
            i++;
        }
        while ( j>= 0)
        {
            if (nums[j] == target)  
                break;
            j--;
        }
        if (i>=nums.size())
        {
            res.push_back(-1);
            res.push_back(-1);
        }else
        {
            res.push_back(i);
            res.push_back(j);
        }
        return res;
    }
};

(2)时间复杂度为O(logn),利用二分查找

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

先找左边界。当mid >= target,将end移动到mid,否则(mid < target),begin = mid+1;

再找右边界。 当mid > target,将end移动到mid,否则(mid <= target),begin = mid+1;最后begin和end可能在target的左面一个。

如果没有数组中target的话,那么left和right会指到同一个值上,否则的话就意味着出现了target,此时left指向第一个出现的target,而right是指向最后一个target的下一个值,所以right需要减去1.

posted @ 2017-03-19 20:11  紫魔戒  阅读(111)  评论(0编辑  收藏  举报