首页 > 代码库 > Search for a Range

Search for a Range

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