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

来源:互联网 发布:淘宝诈骗 济宁 编辑:程序博客网 时间:2024/05/29 02:04

一、题目叙述:

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
原创粉丝点击