Leetcode刷题记——34. Search for a Range(查找一个范围)

一、题目叙述:

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].

Subscribe to see which companies asked this question

二、解题思路:

关键字:二分查找。

1、本题给定一个已经排序好的数组和一个值,要求返回该值在数组中的一个下标范围,使用二分查找,在找不到的情况下,直接返回-1,-1。

2、在找到这个值后,根据返回的位置,分别从返回下标的位置左半边二分查找该值,直到找不到为止,以确定范围最左边的下标;同理去右半边二分查找,以确定范围右边的下标。

三、源码:

import java.util.Arrays;

public class Solution
{
    public int[] searchRange(int[] nums, int target) 
    {
    	int[] result = {-1, -1};
    	if (search(0, nums.length - 1, nums, target) < 0)
    		return result;
    	else
    	{
    		int left, right; 
    		left = right = search(0, nums.length - 1, nums, target);
    		//result[0] = result[1] = mid;
    		while (left >= 0)
    		{
    			result[0] = left;
    			left = search(0, left - 1, nums, target);
    		}
    		while (right >= 0)
    		{
    			result[1] = right;
    			right = search(right + 1, nums.length - 1, nums, target);
    		}
    		
    	}
    	
       return result;
    }
    public int search(int lo, int hi, int[] nums, int target)
    {
         while (lo <= hi)
         {
         	int mid = lo + (hi - lo) / 2;
         	if (nums[mid] < target) lo = mid + 1;
         	else if (nums[mid] > target) hi = mid - 1;
         	else return mid;
         }
         return -1;
    }
    public static void main(String args[])
    {
    	int[] nums = {1,1,1,1,1};
    	Solution solution = new Solution();
    	System.out.println(Arrays.toString(solution.searchRange(nums, 1)));
    
    }
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值