Wednesday, October 9, 2013

Search for a Range [Leetcode]

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

Solution:binary search.

class Solution {
public:
    vector<int> searchRangeHelper(int A[], int begin, int end, int target){
        vector<int> ret;
        if(begin>end){
            ret.push_back(-1); ret.push_back(-1);
            return ret;
        }
        int middle = (begin+end)/2;
        if(A[middle]==target){
            int tmp = middle;
            while(A[tmp]==target && tmp>=begin){ //expand to the left part
                tmp--;
            }
            ret.push_back(tmp+1);
            tmp = middle;
            while(A[tmp]==target && tmp<=end){ //expand to the right part
                tmp++;
            }
            ret.push_back(tmp-1);
            return ret;
        }
        if(A[middle]>target) //search in the left part
            return searchRangeHelper(A, begin, middle-1, target);
        return searchRangeHelper(A, middle+1, end, target); //search in the right part
    }
    vector<int> searchRange(int A[], int n, int target) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        vector<int> ret;
        ret = searchRangeHelper(A, 0, n-1, target);
        return ret;
    }
};

No comments:

Post a Comment