34. Find First and Last Position of Element in Sorted Array

  • Difficulty: Medium

  • Topics: Array, Binary Search

  • Similar Questions:

Problem:

Given an array of integers nums sorted in ascending order, 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].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

Solutions:

bool searchLeft(vector<int>& nums, int index, int target) {
    return nums[index] >= target;
}

bool searchRight(vector<int>& nums, int index, int target) {
    return nums[index] > target || index == nums.size() - 1 || (nums[index] == target && nums[index + 1] > target);
}

class Solution {
public:
    typedef bool (*check) (vector<int>&, int, int);

    vector<int> searchRange(vector<int>& nums, int target) {
        if (nums.size() == 0)   return {-1, -1};
        int leftBound = search(nums, 0, nums.size() - 1, target, &searchLeft);
        int rightBound = search(nums, 0, nums.size() - 1, target, &searchRight);
        return {nums[leftBound] == target ? leftBound : - 1, nums[rightBound] == target ? rightBound : - 1};
    }

    int search(vector<int>& nums, int left, int right, int target, check fn) {
        while (left < right) {
            int mid = left + (right - left) /2 ;
            if ((*fn) (nums, mid, target)) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }

        return left;
    }
};

results matching ""

    No results matching ""