Search for a Range

来源:互联网 发布:猫云seo 编辑:程序博客网 时间:2024/06/07 16:54

Given an array of integers sorted in ascending order, 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].

代码如下:

public class SearchForARange {public int[] searchRange(int[] nums,int target){int i=0,j=nums.length-1;        int[] ret = {-1,-1};        if(nums == null || nums.length == 0)            return ret;        //搜索第一个位置        while(i<j){            int mid = (i+j)/2;            if(nums[mid]<target)                i = mid+1;            else                j = mid;        }                if(nums[i] != target){            return ret;        }else{            ret[0] = i;        }                //搜索最后一个位置        j=nums.length-1;        while(i<j){            int mid = (i+j)/2+1;            if(nums[mid] > target){                j = mid-1;            }else                i = mid;        }        ret[1] = j;                return ret;}}




原创粉丝点击