Leetcode34. Search for a Range

34. Search for a Range

一、原题

Given an array of integers 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].

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


二、题意解析与思路

题目的意思是,给定我们一个递增数组,然后给定我们一个数,要求我们找到这个数在数组中一开始出现的位置

和最后出现的位置。若不存在,则输出[-1,-1]。要求我们的时间复杂度为O(logn)。

该题是一个数组查找的问题,而且要求时间复杂度为O(logn),因此我们可以想到使用二分法因此我的思路是这样的:

1、首先使用二分法找该数的最早出现的位置。

2、获取其最开始出现的位置后,再次用获取的位置和length进行二分获取最后出现的位置。


三、代码

	//寻找目标数最早出现的位置
	public int findLeft(int[] nums, int target, int left, int right) {
		//默认位置为-1
		int indexl = -1;
		while (left <= right) {
        	int middle = (left + right) / 2;
        	if (nums[middle] >= target) {
        		right = middle - 1;
        	} else {
        		left = middle + 1;
        	}
        	//若相等,则赋值
        	if (nums[middle] == target) {
        		indexl = middle;
        	}
        }
		
		return indexl;
	}
	
	//寻找目标数最后出现的位置
	public int findRight(int[] nums, int target, int left, int right) {
		//默认位置为-1
		int indexr = -1;
		while (left <= right) {
        	int middle = (left + right) / 2;
        	if (nums[middle] <= target) {
        		left = middle + 1;
        	} else {
        		right = middle - 1;
        	}
        	
        	if (nums[middle] == target) {
        		indexr = middle;
        	}
        }
		return indexr;
	}
	
	public int[] searchRange(int[] nums, int target) {
       int left = findLeft(nums, target, 0, nums.length - 1);
       int right = findRight(nums, target, left, nums.length - 1);
        
       int[] res = {left, right};
       return res;
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值