Leetcode:给定一个排序整数数组,找出给定目标值的起始和结束位置。 算法的运行时复杂度必须是O(log n)。 如果数组中没有找到目标,返回[- 1,1]。

给定一个已排序的整数数组,使用O(log n)时间复杂度找到目标值的开始和结束索引。如果目标不在数组中,返回[-1, -1]。例如,对于数组[5, 7, 7, 8, 8, 10]和目标值8,返回[3, 4]。解决方案包括线性搜索和二分查找的方法。" 47028907,3211723,Win7操作系统配置FTP服务器指南,"['FTP服务器', 'Windows服务器', '网络服务', 'IIS管理']
摘要由CSDN通过智能技术生成

Given a sorted array of integers, 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].

For example,
Given[5, 7, 7, 8, 8, 10]and target value 8,
return[3, 4].

解题思路:

(1)我们先来看看时间复杂度为O(n)的算法,分别从左遍历和从右遍历数组,找到目标数的第一个下标位置分为是要求解的目标值的起始和结束位置。Java代码实现如下:

public class Solution {
    public int[] searchRange(int[] A, int target) {
        int res[] = new int[2];
        res[0] = -1;
        res[1] = -1;
        //向左找
        for(int i = 0 ; i < A.length; i++){
            if(A[i] == target){
               res[0] = i; 
                break;
            }
        }
       //向右找
        for(int i = A.length - 1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值