LeetCode: Search for a Range

Title:

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

 

思路:肯定是二分,不过对于查找到那个值之后如何处理呢?可以使用一个全局的min,max值。每次查找到相等的那个值,就更新下min,max。使用递归。

class Solution {
public:
    int index_min;
    int index_max;
    Solution(){
        index_min = INT_MAX;
        index_max = -1;
    }
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> result;
        int n = nums.size();
        
        search(nums,target,0,n-1);
        if (index_min == INT_MAX && index_max == -1){
            result.push_back(-1);
            result.push_back(-1);
        }else{
            result.push_back(index_min);
            result.push_back(index_max);
        }
        return result;
    }
    void search(vector<int>& nums, int target, int left, int right){
        if (left <= right){
            int m = (left + right)/2;
            if (nums[m] == target){
                if (m < index_min)
                    index_min = m;
                if (m > index_max)
                    index_max = m;
                search(nums,target,left,m-1);
                search(nums,target,m+1,right);
            }else if (nums[m] > target){
                search(nums,target,left,m-1);
            }else{
                search(nums,target,m+1,right);
            }
        }
    }
};

 如果是求重复元素的次数

int binarySearchRepeated(vector<int> a, int left, int right, int target){
    if (left > right || a.size() < 1)
        return 0;
    int m = (left + right) / 2;
    if (a[m] == target){
        return 1 + binarySearchRepeated(a,left,m-1,target) + binarySearchRepeated(a,m+1,right,target);
    }else if (a[m] > target){
        return binarySearchRepeated(a,left,m-1,target);
    }else{
        return binarySearchRepeated(a,m+1,right,target);
    }
}

 

posted on 2015-04-21 14:28  月下之风  阅读(134)  评论(0编辑  收藏  举报

导航