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

大意:

给定一个排好序的数组,同时给定一个要查找的值 ,找出这个数在数组中的出现在起始和结束位置。算法的时间复杂度要求为log(N)。 如果没有找到就返回[-1, -1]。

思路:

因为时间复杂度的要求,该题使用二分查找,先找到一个值为target的位置,再分别向左右两侧延伸,把所有的位置都找全。详见代码及注释。

代码:

public class Solution {
    public int[] searchRange(int[] nums, int target) {
        if(nums == null || nums.length == 0) {
            return null;
        }

        int[] arr = new int[2];
        arr[0] = -1;
        arr[1] = -1;

        //根据题目对时间复杂度的要求,使用二分查找
        binarySearch(nums, 0, nums.length - 1, target, arr);

        return arr;
    }

    private void binarySearch(int[] nums, int left, int right, int target, int[] arr) {
        //左侧标志位大于右侧标志位,没有找到目标值,返回
        if(right < left) {
            return;
        }

        //碰巧最左侧和最右侧的值相同,且都是target的值,直接返回
        if(nums[left] == nums[right] && nums[left] == target) {
            arr[0] = left;
            arr[1] = right;
            return;
        }

        int mid = (left + right) / 2;

        if(nums[mid] > target) {
            binarySearch(nums, left, mid - 1, target, arr);
        } else if(nums[mid] < target) {
            binarySearch(nums, mid + 1, right, target, arr);
        } else {
            //这两行赋值不能少,假如只有nums[mid] == target,少了这两行后面将会出错
            arr[0] = mid;
            arr[1] = mid;

            //找到左侧的边界
            //注意t1 < left的约束情况不能丢
            int t1 = mid;
            while(t1 > left && nums[t1] == nums[t1 - 1]) {
                t1--;
                arr[0] = t1;
            }

            //找到右侧边界
            int t2 = mid;
            while(t2 < right && nums[t2] == nums[t2 + 1]) {
                t2++;
                arr[1] = t2;
            }
            return;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值