Home Algorithm II | Study Plan | Leetcode
Post
Cancel

Algorithm II | Study Plan | Leetcode

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

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

If target is not found in the array, return [-1, -1].

You must write an algorithm with O(log n) runtime complexity.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        
        int len(nums.size()), first = -1, last = -1;
        int l(0), r(len-1);
        while(l<=r){
            int mid = l + (r - l)/2;
            if(nums[mid] == target)
                first =  mid;
            if(nums[mid] >= target)
                r = mid - 1;
            else
                l = mid + 1;
        }
        
        l = 0, r = len-1;
        while(l<=r){
            int mid = l + (r - l)/2;
            if(nums[mid] == target)
                last =  mid;
            if(nums[mid] > target)
                r = mid -1;
            else
                l = mid + 1;
        }
        
        return {first, last};
    }
};
This post is licensed under CC BY 4.0 by the author.

DSA Part 8: Dynamic Programming

Week 1 | Grind 169 | Blind 75