leetcode-34 Search for a Range

问题描述:

Given a sorted array of integers, find the starting and endingposition 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] andtarget value 8,
return 
[3,4].

 

问题分析:

    有序数组的查找,明显要用到二分查找;而寻找target的范围,则可以转化为求取[start,end];target在数组中出现的第一个位置与最后一个位置的两个经典二分查找的问题;

方法二:

    方法二采取一种取巧的方式,首先依然是查找target出现的第一个位置;查找最后一个位置即可转化为求取target + 1在数组中的第一个位置(这样就可复用前面二分查找代码)index,则target所在位置即为index– 1;这里要注意一个细节,有可能target是数组的最后一位,因此查找要能够返回尾后指针位置;


代码:

方法一:

public class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] result = {-1, -1};
        /** 查找target第一次出现的位置  **/
        int start = 0, end = nums.length - 1;
        int mid = 0;
       
        while (start < end) {
        mid= start + (end - start) / 2;
        if (nums[mid] < target)
             start= mid + 1;
        else
             end= mid;
        }
        if (nums[start] != target)
        return result;
        result[0] = start;
       
        /** 查找target最后出现的位置  **/
        start = 0 ; end = nums.length - 1;;
        while (start < end) {
        mid= start + (end - start) / 2 + 1;
        if (nums[mid] > target)
             end= mid - 1;
        else
             start= mid;
        }
        result[1] = end;
        return result;
   }
}


方法二:

public class Solution {
   public int[]searchRange(int[] A, int target) {
    /** 查找target第一次出现的位置  **/
        int start = Solution.firstGreaterEqual(A,target);
        // 当未查找到,即返回[-1, -1];
        if (start == A.length || A[start] != target) {
            return new int[]{-1, -1};
        }
        /** 这里使用一个技巧复用代码,即查找target+1的位置 index,则对应的target的最后一位即为index - 1**/
        return new int[]{start, Solution.firstGreaterEqual(A, target + 1) - 1};
   }
 
   private static int firstGreaterEqual(int[] A, int target) {
        int low = 0, high = A.length;
        while (low < high) {
            int mid = low + ((high - low) >> 1);
            if (A[mid] < target) {
                low = mid + 1;
            } else {
                high = mid;
            }
        }
        return low;
   }
}


运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值