LeetCode-Find First and Last Position of Element in Sorted Array

本文介绍了一种算法,用于在一个已排序的整数数组中找到给定目标值的起始和结束位置,通过二分查找提高效率,实现了O(logn)的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description:
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]

题意:给定一个按照升序排列的数组,要求找出目标数字所在的下标的范围(目标数字在数组中可能不止一个),并且要求时间复杂度在 O(log n);

解法:既然数组时已经排序好的了,那么我们只要可以找到其中的一个目标数字,从这个数字向两边扩散,就可以找到所有我们想要找到的目标数字了;因此可以先利用二分查找找到其中的一个目标数字;

Java
class Solution {
    public int[] searchRange(int[] nums, int target) {
        if(nums.length == 0){
            return new int[] {-1, -1};
        }
        int left = 0;
        int right = nums.length - 1;
        int mid = (left + right) / 2;
        while(left <= right){
            if(nums[mid] == target) break;
            else if(nums[mid] > target) right = mid - 1;
            else left = mid + 1;
            mid = (left + right) / 2;
        }//find one position of the target digit
        if(nums[mid] != target) return new int[] {-1, -1};
        int st = mid;
        int ed = mid;
        while(st >= 0 || ed < nums.length){
            boolean isMatch = false;
            if(st > 0 && nums[st-1] == target) {st--; isMatch = true;}
            if(ed < nums.length - 1 && nums[ed+1] == target) {ed++; isMatch = true;}
            if(!isMatch) break;
        }
        return new int[] {st, ed};
    }
}
C++
class Solution {//C++
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> result (2, -1);
        if(nums.size() == 0){
            return result;
        }
        int left = 0;
        int right = nums.size() - 1;
        int mid = (left + right) / 2;
        while(left <= right){
            if(nums[mid] == target) break;
            else if(nums[mid] > target) right = mid - 1;
            else left = mid + 1;
            mid = (left + right) / 2;
        }
        if(nums[mid] != target){
            return result;
        }
        int st = mid;
        int ed = mid;
        while(st >= 0 || ed < nums.size()){
            bool isMatch = false;
            if(st > 0 && nums[st-1] == target) {st--; isMatch = true;}
            if(ed < nums.size() - 1 && nums[ed+1] == target) {ed++; isMatch = true;}
            if(!isMatch) break;
        }
        result[0] = st;
        result[1] = ed;
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值