【leetcode】Array——Search for a Range(34)

题目:

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


思路:还是经典的binary search,如果nums[mid]==target,从mid出发,向左右遍历,找范围。但要注意可能会出现out of array range

代码:

    public int[] searchRange(int[] nums, int target) {
        int left=0,right=nums.length-1;
        int [] results = new int [2];
        while(left<=right){
        	int mid = (left+right)/2;
        	if(nums[mid]==target){
        		//search left range
        		int lefttemp = mid;
        		while(nums[lefttemp]==target)
        		{
        			lefttemp--;
        			if(lefttemp==-1)
        				break;
        		}
        		results[0]=lefttemp+1;
        		//search right range
        		int righttemp = mid;
        		while(nums[righttemp]==target)
        		{
        			righttemp++;
        			if(righttemp==nums.length)
        				break;
        		}
        		results[1]=righttemp-1;
        		return results;
        	}
        	if(target<nums[mid])
        		right = mid-1;
        	else
        		left = mid +1;
        }
        //如果没有在循环里面内return,说明没有匹配到target,返回[-1,-1]
    	results[0]=results[1]=-1;
    	return results;
    }
虽然,AC了,但是细想时间复杂度并不是 O(log n)。例如,[1,1,1,1,1,1,1,1],这时候是O(n)。


改进思路1:用binary search查找第一个大于或者等于target的位置,则结果为[ firstGreaterEqual(target), firstGreaterEqual(target+1)-1]

public class Solution {
    public int[] searchRange(int[] A, int target) {
        int start = Solution.firstGreaterEqual(A, target);
        if (start == A.length || A[start] != target) {
            return new int[]{-1, -1};
        }
        return new int[]{start, Solution.firstGreaterEqual(A, target + 1) - 1};
    }

    //find the first number that is greater than or equal to target.
    //could return A.length if target is greater than A[A.length-1].
    //actually this is the same as lower_bound in C++ STL.
    private static int firstGreaterEqual(int[] A, int target) {
        int low = 0, high = A.length;
        while (low < high) {
            int mid = low + ((high - low) >> 1);
            //low <= mid < high
            if (A[mid] < target) {
                low = mid + 1;
            } else {
                //should not be mid-1 when A[mid]==target.
                //could be mid even if A[mid]>target because mid<high.
                high = mid;
            }
        }
        return low;
    }
}
leetcode链接: https://leetcode.com/discuss/19368/very-simple-java-solution-with-only-binary-search-algorithm

改进思路2:分别用binary search查找target第一次出现的位置和最后出现的位置,binary内部的细节很重要,主要是当nums[mid]==target的时候,是向左还是向右,决定了是第一次出现还是最后出现的位置。

public class Solution {
public int[] searchRange(int[] nums, int target) {
    int[] result = new int[2];
    result[0] = findFirst(nums, target);
    result[1] = findLast(nums, target);
    return result;
}

private int findFirst(int[] nums, int target){
    int idx = -1;
    int start = 0;
    int end = nums.length - 1;
    while(start <= end){
        int mid = (start + end) / 2;
        if(nums[mid] >= target){
            end = mid - 1;
        }else{
            start = mid + 1;
        }
        if(nums[mid] == target) idx = mid;
    }
    return idx;
}

private int findLast(int[] nums, int target){
    int idx = -1;
    int start = 0;
    int end = nums.length - 1;
    while(start <= end){
        int mid = (start + end) / 2;
        if(nums[mid] <= target){
            start = mid + 1;
        }else{
            end = mid - 1;
        }
        if(nums[mid] == target) idx = mid;
    }
    return idx;
}
leetcode链接: https://leetcode.com/discuss/52701/easy-java-o-logn-solution点击打开链接


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值