zoukankan      html  css  js  c++  java
  • lintcode61- Search for a Range- medium

    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.

    二分查找法找first target,然后向后检索。

    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) {
            // find the first
            int[] result = new int[2];
            for (int i = 0; i < result.length; i++){
                result[i] = -1;
            }
    
            if (A == null || A.length == 0){
                return result;
            }
    
            int start = 0;
            int end = A.length - 1;
            while (start + 1 < end){
                int mid = start + (end - start) / 2;
                if (target <= A[mid]){
                    end = mid;
                } else {
                    start = mid;
                }
            }
    
            // search forward
            if (A[start] == target){
                result[0] = start;
                result[1] = start;
                while (result[1] + 1 < A.length && A[result[1] + 1] == target){
                    result[1]++;
                }
            } else if (A[end] == target){
                result[0] = end;
                result[1] = end;
                while (result[1] + 1 < A.length && A[result[1] + 1] == target){
                    result[1]++;
                }
            }
            return result;
    
    
        }
    }
  • 相关阅读:
    Winform开发框架之终极应用 伍华聪 博客园
    DZ外部调用登陆
    利用服务定时执行
    winForm写cookie经过
    正则第一天
    NHibernate
    Databases supported by NHibernate
    定时执行
    NHibernate视频教程
    bernate异常及处理方法
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7594807.html
Copyright © 2011-2022 走看看