Monday, June 10, 2013

Leetcode: Search for a Range in C++



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:
vector<int> searchRange(int A[], int n, int target) {
        vector<int> result(2, -1);
        int start =0;
        int end =n-1;
        int mid =0;
        while(start<=end)
        {
            mid = start+(end-start)/2;
            if(A[mid]==target)
            {
                int left = mid;
                int right = mid;
                while(left>=0&&A[left]==target) left--;
                while(right<n&&A[right]==target) right++;
                left++;
                right--;
                result[0] = left;
                result[1] = right;
                return result;
            }
            else if(A[mid]>target)
                end = mid-1;
            else
                start = mid+1;
        }
        return result;
    }

No comments:

Post a Comment