Monday, July 6, 2015

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

题目要求O(logn)的复杂度,很显然是用binary search来解题,找到target的边界,很显然可以利用binary search的变种,找到target的leftmost的index和target的rightmost的index,最后就是答案,需要用到两次binary search。leftmost index 和rightmost index利用left 和right相邻找其中与target相等的值来解。
class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> rst;
        //sanity check
        if (nums.size() == 0) {
            rst.push_back(-1);
            rst.push_back(-1);
            return rst;
        }
        int left = 0;
        int right = nums.size()-1;
        //first: find the left most target
        while (left < right -1) {
            int mid = left + (right - left)/2;
            if (target > nums[mid]) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        int pivot = 0;
        if (nums[left] == target) pivot = left;
        else if (nums[right] == target) pivot = right;
        else {
            rst.push_back(-1);
            rst.push_back(-1);
            return rst;
        }
        rst.push_back(pivot);
        left = 0;
        right = nums.size()-1;
        //second: find the right most target
        while (left < right -1) {
            int mid = left + (right - left)/2;
            if (target >= nums[mid]) {
                left = mid;
            } else {
                right = mid - 1;
            }
        }
        if (nums[right] == target) pivot = right;
        else if (nums[left] == target) pivot = left;
        rst.push_back(pivot);
        return rst;
    }
};

No comments:

Post a Comment