凌云的博客

成功=工作+游戏+少说空话

LeetCode 算法题 34. Search for a Range

分类:algorithm| 发布时间:2016-09-26 23:42:00


题目

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

题意

给出一个有序数组,找出给定数字的开始和结束下标。

你的算法时间复杂度必须大约为 O(log n)。

比如:

给出 [5, 7, 7, 8, 8, 10] 和 数字 8,
返回 [3, 4]。

解法

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int start = greaterEqual(nums, 0, target);
        if (start == nums.size() || nums[start] != target) {
            return { -1, -1 };
        }

        return {start, greaterEqual(nums, start, target + 1) - 1};
    }

    int greaterEqual(vector<int>& nums, int start, int target) {
        int left = start, right = nums.size(), mid;

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

        return left;
    }
};