首页 > 其他 > 详细

Search for a Range

时间:2017-05-04 09:34:31      阅读:269      评论:0      收藏:0      [点我收藏+]

O(logN) 

This question turns to find the first and last element of the target in a sorted array. 

Just be careful with the two result coming out of the while loop. The order to add them to the result is different from the frist/last element questions. 

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[] rst = new int[]{-1, -1};
        if (A == null || A.length == 0) {
            return rst;
        } 
        
       
        //find first element
        int start = 0;
        int end = A.length - 1;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (A[mid] == target) {
                end = mid;
            } else if (A[mid] < target) {
                start = mid;
            } else {
                end = mid;
            }
        } 
        
        if (A[end] == target) {
            rst[0] = end;
        } 
        if (A[start] == target) {
            rst[0] = start;
        }
        
        //find last element 
        start = 0;
        end = A.length - 1;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (A[mid] == target) {
                start = mid;
            } else if (A[mid] < target) {
                start = mid;
            } else {
                end = mid;
            }
        }
        
        if (A[start] == target) {
            rst[1] = start;
        }
        if (A[end] == target) {
            rst[1] = end;
        }
        return rst;
    }
}

 

Search for a Range

原文:http://www.cnblogs.com/codingEskimo/p/6805084.html

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