leetcode——34——Search for a Range

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

自己写的代码,没有真正的实现二分查找,运行速度相对较慢


class Solution {
public:
	vector<int> searchRange(vector<int>& nums, int target) {
		int i = 0;
		int j = nums.size() - 1;
		int mid;
		vector<int> res;
		while (i <= j)
		{
			mid = i + (j - i) / 2;
			if (nums[mid] > target)
			{
				j = mid - 1;
			}
			else if (nums[mid] < target)
			{
				i = mid + 1;
			}
			else
			{ 
				int m = mid, n = mid;
				while (nums[m] == target&&nums[m+1] ==target&&m<nums.size()-1)
				{
					m++;
				}
				while (nums[n] == target&&nums[n-1] == target&&n>0)
				{
					n--;
				}
				res.push_back(n);
				res.push_back(m);
				return res;
			}
		}
		res.push_back(-1);
		res.push_back(-1);
		return res;
	}
};
完全实现二分查找的代码
class Solution {
public:
	vector<int> searchRange(vector<int>& nums, int target) {
		vector<int> res(2, -1);
        if(nums.empty()) return res;
        int high = binarySearchUp(nums, target, 0, nums.size() -1);
        int low = binarySearchLow(nums, target, 0, nums.size() - 1);
        if(high >= low)
        {
            res[0] = low;
            res[1] = high;
            return res;
        }
        return res;

	}
private:
    int binarySearchLow(vector<int>& nums, int target, int begin, int end)
    {
        if(begin > end) return begin;
        int mid = begin + (end - begin) / 2;
        if(nums[mid] < target) return binarySearchLow(nums, target, mid + 1, end);
        else return binarySearchLow(nums, target, begin, mid - 1);
    }
    int binarySearchUp(vector<int>& nums, int target, int begin, int end)
    {
        if(begin > end) return end;
        int mid = begin + (end - begin) / 2;
        if(nums[mid] > target) return binarySearchUp(nums, target, begin, mid - 1);
        else return binarySearchUp(nums, target, mid + 1, end);
    }

};


你可能感兴趣的:(LeetCode,算法题)