欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode算法系列:34. Find First and Last Position of Element in Sorted Array

程序员文章站 2024-03-20 17:33:04
...

题目描述:

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]

算法实现:

这个算法的本质依然是二分法,只不过分两步,第一步找到重复出现元素的最左侧index,第二步找到最右侧的index,这两步都是使用二分法,只不过改变了迭代条件等。

class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> res;
        if(nums.empty()){
            res.push_back(-1);
            res.push_back(-1);
            return res;
        }        
        int i = 0, j = nums.size() - 1, k;
        while(i <= j){            
            k = int((i + j)/2);
            if(i + 1 == j || i == j){
                if(nums[i] == target)res.push_back(i);
                else if(nums[j] == target)res.push_back(j);
                else res.push_back(-1);
                break;
            }
            if(nums[k] >= target) j = k;
            else i = k;
        }
        if(res[0] == -1)res.push_back(-1);
        else {
            i = res[0];
            j = nums.size() - 1;
            while(i <= j || i == j){
                k = int((i + j)/2);
                if(i + 1 == j || i == j){
                    if(nums[j] == target)res.push_back(j);
                    else if(nums[i] == target)res.push_back(i);
                    break;
                }
                if(nums[k] > target) j = k;
                else i = k;
            }
        }
        return res;
    }
};