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

时间:2022-10-03 22:05:10

https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/

 

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]

题解:二分法

代码:

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        int idx = search(nums, 0, nums.size() - 1, target);
        if (idx == -1) return {-1, -1};
        int left = idx, right = idx;
        while (left > 0 && nums[left - 1] == nums[idx]) left --;
        while (right < nums.size() - 1 && nums[right + 1] == nums[idx]) right ++;
        return {left, right};
    }
    int search(vector<int>& nums, int left, int right, int target) {
        int mid;
        while(left <= right) {
            mid = (right - left) / 2 + left;
            if(nums[mid] == target) return mid;
            else if(nums[mid] < target) left = mid + 1;
            else right = mid - 1;
        }
        return -1;
    }
};