首页 > 其他 > 详细

Search for a Range

时间:2016-01-27 07:04:49      阅读:129      评论:0      收藏:0      [点我收藏+]

Given a sorted array of n integers, find the starting and ending position of a given target value.

If the target is not found in the array, return [-1, -1].

Example

Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

Challenge

O(log n) time.

 
Binary Search
 
public class Solution {
    /** 
     *@param A : an integer sorted array
     *@param target :  an integer to be inserted
     *return : a list of length 2, [index1, index2]
     */
    public int[] searchRange(int[] A, int target) {
        // write your code here
        int[] res=new int[]{-1,-1};
        if(A==null || A.length==0||A[0]>target ||A[A.length-1]<target) return res;
        int begin=0;
        int end=A.length-1;while(begin<=end)
        {
            int mid=(begin+end)/2;
            if(A[mid]<target)
            {
                begin=mid+1;
            }
            else if(A[mid]>target)
            {
                end=mid-1;
            }
            else
            {
                begin=mid;
                end=mid;
                while(begin>=0 && A[begin]==target)
                {
                    begin--;
                }
                res[0]=begin+1;
                while(end<A.length && A[end]==target)
                {
                    end++;
                }
                res[1]=end-1;
                break;
            }
        }
        return res;
    }
}

 

Search for a Range

原文:http://www.cnblogs.com/kittyamin/p/5162023.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!