Search for a Range

Posted codingEskimo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

Search for a Range

Search for a Range

Search for a Range

[Leetcode] Search for a Range

Search for a Range

Search for a Range