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;
    
    
        }
    }
  • 相关阅读:
    ACM-ICPC ShangHai 2014
    DEBUG感想
    WireShark 使用日记
    C++ 备忘录
    BZOJ 1022 [SHOI2008]小约翰的游戏John
    高斯消元
    BZOJ3236 [Ahoi2013]作业
    BZOJ P3293&&P1045
    ZKW费用流的理解
    BZOJ 几道水题 2014-4-22
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7594807.html
Copyright © 2011-2022 走看看