码迷,mamicode.com
首页 > 其他好文 > 详细

Search for a Range

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

标签:null   result   ons   target   sorted   solution   blog   add   class   

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

标签:null   result   ons   target   sorted   solution   blog   add   class   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!